1

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?

4
  • Do you have duplicates in a single array, and should they be counted? Commented Aug 6, 2022 at 10:02
  • Or do we need to count the number as duplicate if all tree arrays contain that number? Commented Aug 6, 2022 at 10:06
  • "Kindly guide me..." - This is not how SO works (although there's always some user that ignores that fact...) -> How do I ask and answer homework questions?, How much research effort is expected of Stack Overflow users? Commented Aug 6, 2022 at 10:21
  • Yes I have duplicates in a single array as well and They shoud be counted as well Commented Aug 7, 2022 at 3:14

3 Answers 3

1

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);
Sign up to request clarification or add additional context in comments.

Comments

0

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)

2 Comments

"but I assume" - If you have to "assume" anything then the question is not clear and you should ask for clarification instead of adding an assumption as answer.
I acknowledge. I was pretty sure though
0

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);

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.