Remove original and duplicate from an array of objects - JS

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

    One way to do it, in order to avoid running an exponential loop is to save all values to a new object, and convert that object to a new array.

    const combinedObj = arr.reduce((obj, item) => { obj[item.id] = item; return obj; }, {});
    const newArray = Object.values(combinedObj)
    
    0 讨论(0)
  • 2021-01-28 11:03

    you can sort the data by id,then each item that has different id compared with next element and prev element should be added to the result array.

    const arr = [
      { title: 'sky', artist: 'Jon', id: 1 },
      { title: 'rain', artist: 'Paul', id: 2 },
      { title: 'sky', artist: 'Jon', id: 1 },
      { title: 'sky', artist: 'Jon', id: 1 },
      { title: 'rain', artist: 'Paul', id: 2 },
      { title: 'test', artist: 'test', id: 3 },
    ]
    
    arr.sort((a, b) => a.id - b.id)
    var res = []
    arr.forEach((item, index) => {
      if (index < arr.length - 1 && arr[index + 1]) {
        if (item.id === arr[index + 1].id) {
          return
        }
      }
      if (index > 0 && arr[index - 1]) {
        if (item.id === arr[index - 1].id) {
          return
        }
      }
      res.push(item)
    })
    
    console.log(res)
    

    output

    0: {title: "test", artist: "test", id: 3}
    
    0 讨论(0)
提交回复
热议问题