returning strings instead of numbers [duplicate] - javascript

This question already has answers here:
What is the difference between ( for... in ) and ( for... of ) statements?
(18 answers)
Closed 2 years ago.
I'm trying to write a function (onlyOddNumbers) that accepts an array of numbers and returns a new array with only the odd numbers, it's working but the problem is I'm getting strings in the new array instead of numbers, why this happen ?
let oddNumbersOnly=[]
const filter = function (numbers) {
for (number in numbers){
if(number %2 !==0){
oddNumbersOnly.push(number)
}
} return oddNumbersOnly;
};

use for of instead of for in then convert your num to string
const filter = function(numbers) {
let oddNumbersOnly = []
for (let number of numbers) {
if (number % 2 !== 0) {
oddNumbersOnly.push(number.toString())
}
}
return oddNumbersOnly;
};
const arr = [1, 2, 3, 4, 5, 6];
const result = filter(arr)
console.log(result)

let num = [0, 1, 2, 3, 4, 5, 6];
let oddNumbersOnly = num.filter(numb=>numb%2 !==0);
console.log(oddNumbersOnly);
javaScript has an inbuilt es6 filter function. It is shorter and retain the datatype. You may try this.

Related

Fastest way to check if number is in array? [duplicate]

This question already has answers here:
How do I check if an array includes a value in JavaScript?
(60 answers)
Closed 2 years ago.
I have to create a function that checks if number is in array. So I've tried this:
function getNumber(x, array) {
for (let i = 0; i < array.length; i++) {
if (!x == array[i]) {
console.log(false);
} else if (x == array[i]) {
console.log(true);
}
}
getNumber(4, [5, 10, 2, 3, 5]);
It works just if x is in array but if it's not console doesn't show anything
I want to know if there is easier(faster) way to check it
I think you can try with .includes() - that's definitely easier:
const array = [5, 10, 2, 3, 5];
const check1 = 4;
const check2 = 10;
const getNumber = (check, array) => {
return array.includes(check);
}
console.log(getNumber(check1, array));
console.log(getNumber(check2, array));
I hope this helps!
Use includes
var arr = [5, 10, 2, 3, 5];
if(arr.includes(21)){
console.log(true);
}else{
console.log(false);
}
You could also use indexOf
const array = [5, 10, 2, 3, 5];
const check1 = 4;
const check2 = 10;
const getNumber = (check, array) => {
return array.indexOf(check)>-1;
}
console.log(getNumber(check1, array));
console.log(getNumber(check2, array));
Might be useful if you need higher browser coverage than includes https://caniuse.com/array-includes

Check in an Array if I have three same values, without knowing the value [duplicate]

This question already has answers here:
Get all non-unique values (i.e.: duplicate/more than one occurrence) in an array
(97 answers)
Closed 4 years ago.
I have an array with random numbers, from 1 to 6.
How can I know if I have in this array two, three or four same numbers ? And what is that number ? Or if I have two numbers that they appear twice ?
array = [1, 3, 5, 5, 6];
x = array[0];
repetitions = 0;
for (let i = 0; i < 5; i++) {
const y = array[i];
if (x === y) {
repetitions++;
}
}
Should I do something like this for each element of array ?
Thank you!
This is a simple solution that can be provided using filter;
var array = [1,2, 3,4,4,4,4,4,4,4, 5, 5, 6,6,6];
var duplicate = [];
var newArray = array.filter((v, i) =>{
if(array.indexOf(v) == i){
return v
}else{
duplicate.indexOf(v) == -1 ? duplicate.push(v):'';
}
})
console.log(`new array ${newArray}`);
console.log(`Duplicate values array ${duplicate}`);
There are some constraints you should clarify. For example, this code would returns the first number in the array that is duplicated:
let duplicated = [...array] // makes a copy of the array
.sort() // since `sort` mutate the original
.find((item, index, arr) => value === arr[index + 1]);
console.log(duplicated) // 5, in your case
If there is no number duplicated, then it will return undefined.
However, maybe that is not what you want. Considering this array: [1, 3, 6, 5, 5, 6, 6, 6]. Even if there is also 6 duplicated, you will always return 5.
If you want just to know if there is at least a number duplicated, the code above will works. If you want to know all the duplicated number, and in which order they appear first in the original array, you need something different. For example:
let array = [1, 3, 6, 5, 5, 6, 6, 6];
let occurrences = array
.reduce((acc, value) => (acc[value]=-~acc[value], acc),{});
console.log(occurrences); // {"1": 1, "3": 1, "5": 2, "6": 4}
At this point you can decided what do you want to do with this data, e.g. you can filter out the numbers that appears in the array just once:
console.log(
Object.fromEntries(
Object.entries(occurrences).filter(([num, count]) => count > 1)
)
); // {"5": 2, "6": 4}
etc.
UPDATE (see comments):
Object.fromEntries is a method recently introduced, in case having a filtered object with all the occurrences is the goal, in this context could be easily replaced by a function like this:
const fromEntries = entries =>
entries.reduce((acc, [key, value]) => (acc[key] = value, acc), {});
You check if the value in array exists more than 2 times by compare indexOf and lastIndexOf the value
function duplicates(arr){
let result = []
arr.forEach(item => {
if(arr.indexOf(item) !== arr.lastIndexOf(item)){
result.push(item)
}
})
return [... new Set(result)];
}
console.log(duplicates([1,2,3,5,5,6,6,6]));
You could take a Map and count all occurences of the values.
The result is an array where the first element is the value and the second is the count of the value.
var array = [1, 3, 5, 5, 6],
counts = Array.from(array.reduce((m, v) => m.set(v, (m.get(v) || 0) + 1), new Map));
console.log(counts);
.as-console-wrapper { max-height: 100% !important; top: 0; }

intersection of two arrays which are unique by javascript in simple way [duplicate]

This question already has answers here:
Simplest code for array intersection in javascript
(40 answers)
Closed 4 years ago.
Given two arrays of unequal length:
var array = [1,2,5,1,2,5,5,3];
var array2 = [2,5,5,3,1,10];
How can I find the values common in both arrays? In this case, output should be "1, 2, 5, 3".
While you like to get unique items of common values, you could use a Set for both arrays and filter the unique values.
This proposal returns a different result as the above duplication target.
function getCommon(a, b) {
return [...new Set(a)].filter(Set.prototype.has, new Set(b));
}
var a = [1, 2, 5, 1, 2, 5, 5, 3],
b = [2, 5, 5, 3, 1, 10];
console.log(getCommon(a, b));
In javascript you can use these tow functions
function intersect(a, b) {
return a.filter(Set.prototype.has, new Set(b));
}
function removeDuplicates(arr){
let unique_array = []
for(let i = 0;i < arr.length; i++){
if(unique_array.indexOf(arr[i]) == -1){
unique_array.push(arr[i])
}
}
return unique_array
}
var array1=intersect([1,2,5,1,2,5,5,3], [2,5,5,3,1,10]);
console.log(array1);
console.log(removeDuplicates(array1));

trying to get a quantity of absent elements in the array [duplicate]

This question already has answers here:
Why is math.max() returning NaN on an array of integers?
(5 answers)
Closed 5 years ago.
i am trying to handle with an array with non-consecutive numbers . Here is my example var myArray = [2, 4, 6, 8] . absent numbers are 3, 5, 7 and the quantity = 3 . I tried to get it with this function `
function makeArrayConsecutive(myArray) {
return Math.max(myArray) - Math.min(myArray) + 1 - myArray.length;
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));
this must return 3 ... but it returns NaN... whats the issue ?
Here's one solution that I think would work for you:
function makeArrayConsecutive(arr) {
//get the min and max using reduce
var max = arr.reduce(function(a, b) {
return Math.max(a, b);
});
var min = arr.reduce(function(a, b) {
return Math.min(a, b);
});
//amount of numbers b/t min/max if array had no "gaps"
var deltaDesired = ((max - min) - 1);
//actual amount of numbers b/t min/max in our array
var deltaActual = (arr.length - 2);
return (deltaDesired - deltaActual);
}
var myArray = [2, 4, 6, 8];
console.log(makeArrayConsecutive(myArray));

How do you use the forEach method in Javascript to increment each value in the array by 5? [duplicate]

This question already has answers here:
Loop (for each) over an array in JavaScript
(40 answers)
Closed 5 years ago.
How do you use the forEach method in Javascript to increment each value in the array by 5? Can someone please give me an example, I'm confused on how to use the syntax for forEach in this situation.
You should use the Array#map function instead of forEach to increment all the values of your array by 5:
const array = [1, 2, 3, 4];
const result = array.map(a => a + 5);
console.log(result);
map() is a better option in this case . see the below sample and fiddle
var numbers = [1, 5, 10, 15];
var newnum = numbers.map(function(x) {
return x + 5;
});
console.log(newnum);
or you can also use arrow function syntax for ES2015
var numbers = [1, 5, 10, 15];
var newnum = numbers.map(x => x + 5);
console.log(newnum);
link to fiddle :
https://jsfiddle.net/vjzbo9ep/1/
If the goal is to apply Array.forEach function to increment each value in the array by 5 while modifying the initial array in-place, use the following:
var arr = [2, 3, 4];
arr.forEach(function(v, i, a){ a[i] += 5; });
console.log(arr);

Categories