0

I need to know if an array of objects contains at least two same objects in it, in JavaScript.

I have a form that allow people to create questions (title, description, type, answer options). I need to check whether the user has entered multiple answer options with the same label. They are stored in an array.

// The array of answer options
let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]

I tried using array.indexOf({value: 'a'}) and array.lastIndexOf({value: 'a'}) but they both give me an index of -1.

5 Answers5

1

Separate objects are never === to each other, so you'll have to use a different method. One option is to create a Set of the stringified objects, and return true once any duplicate string is found:

const hasDupes = (arr) => {
  const strings = new Set();
  for (const obj of arr) {
    const string = JSON.stringify(obj);
    if (strings.has(string)) {
      return true;
    }
    strings.add(string);
  }
  return false;
};
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}]));
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]));
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320
1

If you are only concerned about the value property and you use case is not more complex and you can simply do this in one line via:

let hasDupes = arr => new Set(arr.map(x => x.value)).size !== arr.length

console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'},{value: 'a'}]))
console.log(hasDupes([{value: 'a'}, {value: 'b'}, {value: 'c'}]))

You would use Set to add the values of value and if the size of it is smaller than the actual input array length than you had duplicates. There is no need to do JSON.stringify, compare strings etc if you only care about that one property being checked.

Also JSON.stringify has issues when comparing equality of objects.

Akrion
  • 18,117
  • 1
  • 34
  • 54
0

Use findIndex:

let array = [{value: 'a'}, {value: 'b'}, {value: 'c'}, {value: 'a'}];
const index = array.findIndex(({ value }) => value == "a");
console.log(index);
Jack Bashford
  • 43,180
  • 11
  • 50
  • 79
  • This gives me the index of the first occurence right? I would like to know if there are multiple `{value: 'a'}`, not just the index of the first one. –  May 27 '19 at 23:33
0

indexOf will return the instance of an object

{value: 'a'} !== {value: 'a'};

as they are both different instances of objects.

You can find the object

const obj = array.find(item => item.value === 'a')
Adrian Brand
  • 20,384
  • 4
  • 39
  • 60
0

You can use lodash.js to compare two objects. Please see the sample below.

let array = [{ value: "a" }, { value: "b" }, { value: "c" }, { value: "a" }];

const object = { value: "a" };

countObjOccurrences = object => {
  let occurances = 0;
  array.map(item => {
    if (_.isEqual(item, object)) {
      occurances += 1;
    }
  });
  return occurances;
};

This function will return 2.

Ken Labso
  • 885
  • 9
  • 13