Need To Find Or Count Duplicates In Multidimensional Array
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']] Suggestions: Count can be
Solution 1:
My answer from the original question (except that I've got three items like [3, "df"]
in the input array) is:
const input = [
[2, "sk"], [3, "df"], [7, "uz"], [3, "df"], [7, "gh"],
[5, "df"], [21, "sk"], [2, "1sk"], [3, "df"]
];
const duplicate_count = input.length - newSet( input.map(JSON.stringify) ).size;
console.log(duplicate_count);
If the count for [[3,"df"],[3,"df"],[3,"df"]]
should be one instead of two then perhaps something like:
const input = [
[2, "sk"], [3, "df"], [7, "uz"], [3, "df"], [7, "gh"],
[5, "df"], [21, "sk"], [2, "1sk"], [3, "df"]
];
const duplicate_count = [
...input
.map(JSON.stringify)
.reduce( (acc, v) => acc.set(v, (acc.get(v) || 0) + 1), newMap() )
.values()
].filter((v) => v > 1).length;
console.log(duplicate_count);
Solution 2:
You could map
to concatenate the numbers and strings, then sort
. Finally, reduce
the array to the duplicates count.
const input = [
[2, "sk"],
[3, "df"],
[7, "uz"],
[3, "df"],
[7, "gh"],
[7, "df"],
];
const result = input
.map(([number, string]) => number + string)
.sort()
.reduce(
(acc, cur, i, { [i - 1]: last }) => (cur === last ? acc + 1 : acc),
0
);
console.log(`Count: ${result}${result && ' Alert duplicate data found'}`);
Solution 3:
let arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"],[2,"sk"],[7,"uz"]]
functiongetNumDupes(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');
Solution 4:
You can use forEach
to iterate the array and then filter and check length if found more than 1, set an entry into Map which holds a key value pair and will keep 1 entry for same key and then can check the size.
let arr =[[2,"sk"],[3,"df"],[7,"uz"],[3,"df"],[7,"gh"]];
let map = newMap();
arr.forEach(e1 =>
arr.filter(e2 => e1[0]===e2[0] && e1[1]===e2[1]).length > 1
? map.set(`${e1[0]}-${e1[1]}`,1)
: null
);
console.log(`${map.size} duplicate found`);
Post a Comment for "Need To Find Or Count Duplicates In Multidimensional Array"