简体   繁体   中英

Get unique values from an array of objects using Cofeescript

I have an array that looks like this:

[
  {
    "id": 1,
    "name": "Paul",
    "parent": "Jane"
  }, 
  {
    "id": 2,
    "name": "Paul",
    "parent": "Jack"
  },
  {
    "id": 3,
    "name": "Mike",
    "parent": "Janice"
  },
]

And every time the parent value is repeated I would like to show only the first element, like this:

[
  {
    "id": 1,
    "name": "Paul",
    "parent": "Jane"
  }, 
  {
    "id": 3,
    "name": "Mike",
    "parent": "Janice"
  },
]

How can I accomplish this using cofeescript? Thank you so much!

Hi not sure regarding cofeescript, but in typescript this would work:

/**
* usage example:
* var items = [{id: 1}, {id: 2}, {id: 2},{id: 3}];
* var test = uniqueArray(items);
* @param items []
*/
export function uniqueArray<T>(items: T[]): T[] {
  return [...new Map(items.map((item: any) => [item['name'], item])).values()];
}

Again not sure how coffeescript works with their Map function but, maybe there is a semilliar way of work in coffee-script. If not.... you can ignore this:P

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