Home > OS >  how to return duplicates elemements from object array
how to return duplicates elemements from object array

Time:01-27

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

how can I return items that have the same name and age?

im trying something like this but it return every element on array

data.some(d => {
for (const it of form) {
if (it.name == d.name && it.age == d.age) {
arr.push(it)....

CodePudding user response:

You have to make sure that you are not comparing to the same item, where properties always match:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];

const res = data.filter(item => data.some(i => i !== item && item.name === i.name && item.age === i.age))
console.log(res)

If you don't want the first occurrence, you have to check against the already processed elements:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];


const [result, _] = data.reduce(([duplicates, checked], el) => {
    checked.some(i => el.name === i.name && el.age === i.age) && duplicates.push(el)
    return [duplicates, [...checked, el]]
  }, [[], []]
)
console.log(result)

Sort-based approaches are very efficient with that sort of problem:

data= [
  { "id": 0, "name": "name1", "age": 12, "city": "cityA" },
  { "id": 1, "name": "name2", "age": 7, "city": "cityC" },
  { "id": 2, "name": "name3", "age": 23, "city": "cityB" },
  { "id": 2, "name": "name1", "age": 12, "city": "cityA" }
];
const sorted = data.sort( (e1, e2) => e1.name.localeCompare(e2.name) || e1.age - e2.age)
const result = sorted.filter( (el, i) => i > 0 && sorted[i-1].name === el.name && sorted[i-1].age === el.age)
console.log(result)

  • Related