1

I want to find number a duplicates and it's name in array of objects in javascript.

I checked related questions but none help in finding the exact duplicate count. Even they do not focus on finding it if there are multiple duplicates

I tried this which will throw message on finding duplicates. But i want the count of duplicates and handle the case when there are multiple duplicates with count of each name occuring multiple times.

My code:

let keyArr = this.customPropertiesArray.map(function (item: any) { return item.name });
 let isDuplicate = keyArr.some(function (item: any, idx: any) {
      return keyArr.indexOf(item) != idx
 });
 if (isDuplicate) {
     console.log("Duplicate found");
 }

The array could be something like this:

let array=[
{"name":"name1","value":"value1"},
{"name":"name2","value":"value2"},
{"name":"name1","value":"value42"},
{"name":"name2","value":"value52"},
{"name":"name3","value":"value2"},
{"name":"name2","value":"value2"}...];

I want a message something like "name1 is duplicate occuring 2 times" and "name2 is duplicate occuring 3 times"

1
  • Yes I want it to be supported in majority of browsers. Just in case if you are using any new features of javascript. Commented Apr 28, 2017 at 7:10

2 Answers 2

1

You could just count the names in an object.

var array = [{ name: "name1", value: "value1" }, { name: "name2", value: "value2" }, { name: "name1", value: "value42" }, { name: "name2", value: "value52" }, { name: "name3", value: "value2" }, { name: "name2", value: "value2" }],
    count = Object.create(null);

array.forEach(function (o) {
    count[o.name] = (count[o.name] || 0) + 1;
});

Object.keys(count).forEach(function (k) {
    if (count[k] > 1) {
        console.log(k + ' is duplicate occuring ' + count[k] + ' times.');
    }
});

console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

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

Comments

0

This will list your duplicates:

let array=[
{"name":"name1","value":"value1"},
{"name":"name2","value":"value2"},
{"name":"name1","value":"value42"},
{"name":"name2","value":"value52"},
{"name":"name3","value":"value2"},
{"name":"name2","value":"value2"}];

const counts = array.reduce((accum, current) => {
  accum[current.name] = (accum[current.name] || 0) + 1;
  return accum;
}, {});

Object.keys(counts)
  .filter(key => counts[key] > 1)
  .forEach(grp => console.log(`${grp} is duplicate occurring ${counts[grp]} times`));

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.