1

I have an array of objects. Each object has two fields "type" and "position". I want to know if there are any objects (in this array) with same "type" and "position" (and get it). How can I realize it? I know how to filter array, but how to compare with other objects?

var array = forms.filter(function (obj) { return obj.type === 100 });

  • Please refer https://www.w3schools.com/jsref/jsref_filter.asp – Dilip Belgumpi Oct 23 '18 at 12:26
  • Possible duplicate of [Remove duplicates from an array of objects in JavaScript](https://stackoverflow.com/questions/2218999/remove-duplicates-from-an-array-of-objects-in-javascript) – choz Oct 23 '18 at 12:27
  • @DilipBelgumpi be careful providing w3schools links, since some of them are, sometimes, incredibly outdated. Refer the official MDN documentation instead, where possible. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter – briosheje Oct 23 '18 at 12:28
  • do you want to get duplicate items or unique items? – Nina Scholz Oct 23 '18 at 12:28
  • @NinaScholz I need to get duplicate items – Nikita Kazeichev Oct 23 '18 at 12:32

2 Answers2

1

You could take a Map, group same type/postion objects and filkter the grouped result for length greater than one.

var data = [{ type: 'a', position: 1 }, { type: 'b', position: 1 }, { type: 'a', position: 1 }, { type:'a', position: 2 }, { type: 'b', position: 2 }, { type: 'c', position: 1 }, { type:'c', position: 1 }],
    duplicates = Array
        .from(
            data
                .reduce((m, o) => {
                    var key = ['type', 'position'].map(k => o[k]).join('|');
                    return m.set(key, (m.get(key) || []).concat(o));
                }, new Map)
               .values()
        )
       .filter(({ length }) => length > 1);

console.log(duplicates);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
1

This is another way to do it:

const data = [
  { type: 'a', position: 1 },
  { type: 'b', position: 1 },
  { type: 'a', position: 1 },
  { type: 'a', position: 2 },
  { type: 'b', position: 2 },
  { type: 'c', position: 1 },
  { type: 'c', position: 1 }
]

const duplicates = data =>
  data.reduce((prev, el, index) => {
    const key = JSON.stringify({ p: el.position, t: el.type })
    prev[key] = prev[key] || []
    prev[key].push(el)
    if (index === data.length - 1) {
      return Object.values(prev).filter(dups => dups.length > 1)
    }
    return prev
  }, {})

console.log(duplicates(data))
lipp
  • 5,586
  • 1
  • 21
  • 32