简体   繁体   中英

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

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
  }
}, []);

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))

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM