I have two arrays in input,
var array1 = [1,2,3,4,5,6];
var array2 = [3,4,6,8];
Output should be:
var finalArray = [1,2,5,8];
Please suggest me a solution using javascript. I want to iterate on array1.
I have two arrays in input,
var array1 = [1,2,3,4,5,6];
var array2 = [3,4,6,8];
Output should be:
var finalArray = [1,2,5,8];
Please suggest me a solution using javascript. I want to iterate on array1.
You can use array.prototype.filter
and array.prototype.concat:
var arr1 = [1,2,3,4,5,6];
var arr2 = [3,4,6,8];
var res = [].concat(
arr1.filter(e => !arr2.includes(e)),
arr2.filter(e => !arr1.includes(e))
);
console.log(res);
And even shorter with ES6 spread
:
var arr1 = [1,2,3,4,5,6];
var arr2 = [3,4,6,8];
var res = [...arr1.filter(e => !arr2.includes(e)), ...arr2.filter(e => !arr1.includes(e))];
console.log(res);
Use filter
and concat
var output = array1.filter( s => !array2.includes(s) )
.concat(
array2.filter( s => !array1.includes(s) ) )
Demo
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [3, 4, 6, 8];
var output = array1.filter(s => !array2.includes(s)).concat(array2.filter(s => !array1.includes(s)));
console.log(output);
Explanation
1) First, filter
out the values from array1
which are in array2
2) Second, filter
out the values from array2
which are in array1
3) concat
1) and 2)
You could use .filter()
to filter your arrays for containing any elements, which are also contained in the other array and then combine them using .concat()
:
var array1 = [1, 2, 3, 4, 5, 6];
var array2 = [3, 4, 6, 8];
var arr1 = array1.filter(e => !array2.find(f => f == e));
var arr2 = array2.filter(e => !array1.find(f => f == e));
var arr = arr1.concat(arr2);
console.log(arr);
You can try with Array's filter()
and concat()
:
var array1 = [1,2,3,4,5,6];
var array2 = [3,4,6,8];
var res = array1.filter( i => !array2.includes(i));
var temp = array2.filter( i => !array1.includes(i));
res = res.concat(temp)
console.log(res);