I have 3 arrays within a array
Arr = [[arr1],[arr2],[arr3]]
Now I have to find the duplicates in these arrays ([arr1],[arr2],[arr3]) and store the duplicate values in another array.
Arr2 = [ Duplicate values of arr 1,2,,3 ]
how to do it in JavaScript?
CodePudding user response:
At first I though to concatenate the arrays into 1 big one, but I assume you want the duplicates that appear in all arrays so:
var arr1 = [1, 2, 3, 4]
var arr2 = [1, 2, 4, 8]
var arr3 = [2, 4, 6, 8]
var duplicates = [];
arr1.forEach(function(item) {
// you could change the && to || if you want
if ((arr2.indexOf(item) > -1) && (arr3.indexOf(item) > -1)) {
duplicates.push(item)
}
})
console.log("" duplicates)
CodePudding user response:
This is one of many other solutions you can do
const a = [
[1,1,2,1,3],
[2,1,4,4,5],
[3,1,4,5,1]
];
// flat the two dimensions array to one dimension array
const transformedArray = a.flat();
const unifiedArray = [];
const countDuplicates = [];
// create a new array containing unique values
// you can use the Set(..) object for this too
transformedArray.forEach(elem => {
if(!unifiedArray.includes(elem)) {
unifiedArray.push(elem);
}
});
// start counting
unifiedArray.forEach(elem => {
const countElem = transformedArray.filter(el => el === elem).length;
countDuplicates.push({
element: elem,
count: countElem
});
});
// test values
console.log(transformedArray);
console.log(countDuplicates);
CodePudding user response:
this is simple solution of your question
const arr1 = [2, 3, 4, 5, 6, 7, 8];
const arr2 = [1, 2, 3, 9];
const arr3 = [11, 2, 3, 12, 13];
const duplicates = arr1.filter((i) => arr2.includes(i) && arr3.includes(i));
console.log(duplicates);