Example:
myArray = [[1,2,3,4],
[2,3,4,5],
[3,4,5,6]
];
Expected output:
newArray = [3,4]
How do I generate a new array with the values present in all 3 arrays?
While reducing, return an intersection of the accumulator with the current sub-array being iterated over:
const myArray = [[1,2,3,4], [2,3,4,5], [3,4,5,6]]; const intersection = myArray.reduce((a, arr) => ( a.filter(num => arr.includes(num)) )); console.log(intersection);
You can use .filter()
to extract the matching values:
let myArray = [[1, 2, 3, 4], [2, 3, 4, 5], [3, 4, 5, 6]]; let intersect = ([f, ...r]) => f.filter(v => r.every(a => a.includes(v))); console.log(intersect(myArray));
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.