0

I need to count the no of duplicates in an multidimensional array and give alert if duplicates found.

Arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]]

Only exact count require like [3,"df"] at 2 nd position equals [3,"df"], at 4 th position Expected Output Count :1 Alert duplicate data found

5
  • If the input array was [[2,"sk"],[5,"df"],[7,"uz"],[3,"df"],[7,"gh"]] would this have one duplicate or no duplicates? ([5,"df"] vs [3,"df"]) Commented Jun 12, 2021 at 21:14
  • No these duplicates not counted Commented Jun 12, 2021 at 21:16
  • What about [2,"sk"] and ["sk",2]? Commented Jun 12, 2021 at 21:26
  • Would it be possible to have a [21, "sk"] and a [2, "1sk"]? Commented Jun 12, 2021 at 21:28
  • Need perfect combination [2,"sk"] must be equal to [2,"sk"] then only it counts Commented Jun 12, 2021 at 21:32

3 Answers 3

1

You could map to a stringified version of the inner arrays and then create a Set of these and then calculate the difference in length of the items in the set and the original array:

const input = [
  [2, "sk"], [3, "df"], [7, "uz"], [3, "df"], [7, "gh"],
  [5, "df"], [21, "sk"], [2, "1sk"]
];

const duplicate_count = input.length - new Set( input.map(JSON.stringify) ).size;

console.log(duplicate_count);

Sign up to request clarification or add additional context in comments.

1 Comment

Always first value is no and second is string Only counts the exact combination Like [3,"df"] at second position equal to [3,"df"] at fourth combination
0

You could map to get only the values, then sort, then count duplicates with reduce like this:

const input = [
  [2, "sk"],
  [3, "df"],
  [7, "uz"],
  [3, "df"],
  [7, "gh"],
];

const result = input
  .map(([, value]) => value)
  .sort()
  .reduce(
    (acc, cur, i, { [i - 1]: last }) => (cur === last ? acc + 1 : acc),
    0
  );

console.log(`Count: ${result}${result && ' Alert duplicate data found'}`);

Comments

0

Here's a simple little function to return the number of dupes found

let arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"],[2,"sk"],[7,"uz"]]

function getNumDupes(a) {
   return a.length-
arr.reduce((b,a)=>{if (!b.includes(a.join(""))) b.push(a.join("")); return b;},[]).length 
}

console.log(getNumDupes(arr) + ' duplicates found');

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.