get only the unique value of an array

后端 未结 5 1811
星月不相逢
星月不相逢 2021-01-14 09:16

I am new to javascript and I tried like using distinct but its not what im looking for

example array:

let arr = [ {key:\"1\",value:\"dog\"},
                 


        
5条回答
  •  执笔经年
    2021-01-14 09:31

    You can map your objects to stringified versions of your objects so you can then use .indexOf and .lastIndexOf() to compare if the object found appears in different locations in your array, if the last and first index appear in the same location then it can be said that they're the same object (ie: a duplicate doesn't exist) and can be kept in your resulting array like so:

    const arr = [{key:"1",value:"dog"},{key:"1",value:"dog"},{key:"2",value:"cat"},{key:"3",value:"bird"},{key:"3",value:"bird"}];
    
    const searchable = arr.map(JSON.stringify);
    const res = arr.filter((obj, i) => {
      const str = JSON.stringify(obj);
      return searchable.indexOf(str) === searchable.lastIndexOf(str);
    });
    console.log(res);

提交回复
热议问题