Remove original and duplicate from an array of objects - JS

前端 未结 8 1602
时光取名叫无心
时光取名叫无心 2021-01-28 10:40

I have an array of objects.

const arr = [
  { title: \"sky\", artist: \"Jon\", id: 1 },
  { title: \"rain\", artist: \"Paul\", id: 2 },
  { title: \"sky\", artis         


        
8条回答
  •  情深已故
    2021-01-28 10:54

    If you know the title, artist, id are gonna be in the same order in each of the object, one solution can be this:

    var arrayX=[
      { title: "sky", artist: "Jon", id: 1 },
      { title: "rain", artist: "Paul", id: 2 },
      { title: "sky", artist: "Jon", id: 1 }
    ];
    var newArray = arrayX.map(i=> JSON.stringify(i)); //stringify all the objects so as to compare them
    var res = newArray.filter((elem, index)=>{
      if(newArray.indexOf(elem) === newArray.lastIndexOf(elem)){
        return elem //get only those elements whihc do not have dupes
      }
    }); 
    var finalResult = res.map(i=>JSON.parse(i)); //parse the result to get the array of object
    console.log(finalResult)

提交回复
热议问题