Remove original and duplicate from an array of objects - JS

前端 未结 8 1464
时光取名叫无心
时光取名叫无心 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:48

    You could run the array through reduce() and then use some to see if you should add if it does not exist, or remove using filter if it does.

    Snippet:

    const arr = [
      { title: "sky", artist: "Jon", id: 1  },
      { title: "rain", artist: "Paul", id: 2  },
      { title: "sky", artist: "Jon", id: 1  },
      { title: "rain", artist: "Paul", id: 2  },
      { title: "earth", artist: "Frank", id: 3  },
    ];
    
    const unique = arr.reduce((accumulator, currentValue) => { 
      // add if we don't have
      if (!accumulator.some(x => x.id === currentValue.id)) {
        accumulator.push(currentValue);
      } else {
        // remove if we do
        accumulator = accumulator.filter(x => x.id !== currentValue.id);
      }
      
      return accumulator;
    }, []); 
    
    console.info(unique);

提交回复
热议问题