Home > database >  How to retrieve the array of objects having same property value in javascript
How to retrieve the array of objects having same property value in javascript

Time:04-09

I have a array of object if property items has same value, return that array object in javascript

In the below list, retrieve the array of object having same value in

items property in javascript

note:also dynamic object array, items value may vary, so cannot directly filter with value

var list =[
  {id: 1, name: "dev", items: "sales", code: "IN"},
  {id: 2, name: "lena", items: "finance", code: "SG"}
  {id: 3, name: "lisa", items: "sales", code: "AU"},
  {id: 4, name: "mano", items: "marketing", code: "IN"}
]

Expected Result
 {id: 1, name: "dev", items: "sales", code: "IN"}
 {id: 3, name: "lisa", items: "sales", code: "AU"},


var result= list.reduce((m, o) => {
  const found= m.find(e => e.items === o.items);
  if(found){
   m.push(o);
   return m
  }
}, []);

CodePudding user response:

With reduce it's more cumbersome to find out all duplicates. You can use closure.

const list = [
  { id: 1, name: "dev", items: "sales", code: "IN" },
  { id: 2, name: "lena", items: "finance", code: "SG" },
  { id: 3, name: "lisa", items: "sales", code: "AU" },
  { id: 4, name: "mano", items: "marketing", code: "IN" },
  { id: 5, name: "lisa", items: "gul gul", code: "AU" },
  { id: 6, name: "anthony", items: "some", code: "AU" },
  { id: 7, name: "mark", items: "gul gul", code: "AU" }
];

const findByItems = (eq) => (arr) => arr.filter(
  (x, i) => arr.find((y, j) => i !== j && eq(x, y))
)

const duplicatedItems = findByItems((a, b) => a.items === b.items);


console.log(duplicatedItems(list))

CodePudding user response:

I would personally group the items in the input by their items values, and then extract the one with the longest group (in your example, finance and marketing would have one item and only sales would have two):

var list = [
  {id: 1, name: "dev", items: "sales", code: "IN"},
  {id: 2, name: "lena", items: "finance", code: "SG"},
  {id: 3, name: "lisa", items: "sales", code: "AU"},
  {id: 4, name: "mano", items: "marketing", code: "IN"}
]

const map = {}
for (let item of list) {
  if (map[item.items]) {
    map[item.items].push(item);
  } else {
    map[item.items] = [item]
  }
}

let maxLength = 0, result;
for (let key in map) {
  if (map[key].length > maxLength) {
    maxLength = map[key].length
    result = map[key]
  }
}

console.log(result)

This will return

[
  { id: 1, name: 'dev', items: 'sales', code: 'IN' },
  { id: 3, name: 'lisa', items: 'sales', code: 'AU' }
]

as you were expecting.

  • Related