Home > other >  Extracting common numbers from multi-dimensional array
Extracting common numbers from multi-dimensional array

Time:07-21

I'm a little stuck on a JavaScript function that can extract common numbers from a nested array of numbers.

Example input:

[[7, 3, 6, 10], [9, 10, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];

Expected output:

[3, 10]; // because 3 and 10 are present in all 3 arrays

It must work with any arbitrary array of numbers of any size.

Ideas?

CodePudding user response:

It might pay to convert the inner arrays into ever shrinking Sets:

const arr = [[7, 3, 6, 10], [9, 10, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];

// Expected output:  [3, 10]; // because 3 and 10 are present in all 3 arrays


let final = new Set(arr[0])

for ( i=1; i < arr.length ; i  ) {
  final = new Set (arr[i].filter ( x => final.has(x) ))
}

const newArr = Array.from(final)

console.log(newArr)

CodePudding user response:

You can do something like this:

var arr = [[7, 3, 6, 10], [9, 10, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];

var result = arr.shift().filter(function(v) {
    return arr.every(function(a) {
        return a.indexOf(v) !== -1;
    });
});

console.log(result);

CodePudding user response:

var arrays = [[7, 3, 6, 10], [9, 10, 3], [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]];

var result = arrays.shift().reduce(function(res, v) {
    if (res.indexOf(v) === -1 && arrays.every(function(a) {
        return a.indexOf(v) !== -1;
    })) res.push(v);
    return res;
}, []);

document.write('<pre>'   JSON.stringify(result,null,4)  '</pre>');
  • Related