This seems like a very straightforward problem but for the life of me, I can not get it sorted.
I want to compare two arrays and if the value of array2 is in array1 push it to a new array otherwise push a 0.
these are my arrays:
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let arrayTwo = [3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16];
desired outcome is
[0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]
current attempt with obvious indices issues
let newArray = [];
for (let i=0; i < arrayOne.length; i++){
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
else newArray.push(0);
};
current result
[0, 0, 0, 8, 9, 10, 0, 0, 13, 14, 15, 16, undefined, undefined, undefined, undefined, undefined, 0]
Issue with your approach is that you are searching for an index in arrayTwo
if(arrayTwo.includes(i)) newArray.push(arrayTwo[i]);
where i is the index not a value. That's why you are getting undefined values, because arrayTwo has less values then arrayOne, so index of arrayOne will not exists in arrayTwo.
Instead you should search for value in arrayTwo
for (let i=0; i < arrayOne.length; i++){
let value = arrayOne[i];
if(arrayTwo.includes(value)) newArray.push(value);
else newArray.push(0);
};
If you check only for existence of the value in collection - use Set which designed exactly for this purpose.
let arrayOne = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18];
let values = new Set([3, 4, 5, 8, 9, 10, 12, 13, 14, 15, 16]);
const result = arrayOne.map(value => values.has(value) ? value : 0);
// => [0,0,3,4,5,0,0,8,9,10,11,12,13,14,15,16,0,0]