I am trying to achieve a check for duplication and push items to array in the below code the functionality works well but instead of using a null is there any other way of doing it
array2.forEach((item) =>
array1.includes(item)
? null
: array1.push(item),
);
CodePudding user response:
You can use &&
to short circuit the operation
const array1 = [1, 2, 3, 4, 5, 6],
array2 = [4, 5, 6, 7, 8, 9, 10];
array2.forEach((item) => !array1.includes(item) && array1.push(item));
console.log(array1)
CodePudding user response:
You can use a set
const set = new Set();
const brr = ["one","one"].forEach(item=> set.add(item));
Array.from(set)
// --> ["one"]
CodePudding user response:
this should works:
array1.push( ... array2.filter(item => !array1.includes(item) ) )
or you can switch arrays to Set()'s and use:
array2.forEach( item => array1.add(item) )
CodePudding user response:
You can use ES6 features like spread operator(...) and Set
let array1 = [1,2,3,4,5,6];
let array2 = [4,5,6,7,8,9,10];
const mergedArrays = [...array1, ...array2];
array1 = [...new Set(mergedArrays)]; // make the array elements unique
console.log(array1);
CodePudding user response:
you can use "undefined" instead of "null", undefined means do nothing, and null is by itself a value.
ar
ray2.forEach((item) =>
array1.includes(item)
? undefined
: array1.push(item),
);