js 数组对象去掉相同的

原始数据:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
dataContent: (...)
topic: "年龄"
1:
dataContent: (...)
topic: "性别"
2: 
dataContent: (...)
topic: "性别"
3: {__ob__: Observer}
4: {__ob__: Observer}

删除数组对象 topic 字段相同的,图中有两个topic:性别,只想留住后面的,要删除前面那个topic:性别的,把下标为1的删除 留下标为2的
期望得到:

(20) [{…}, {…}, {…}, {…}, {…}, {…}, __ob__: Observer]
0:
dataContent: (...)
topic: "年龄"
2: 
dataContent: (...)
topic: "性别"
3: {__ob__: Observer}
4: {__ob__: Observer}

更新: topic字段值不固定

阅读 5.6k
5 个回答
// 传key值和value值数组
function (keys, value) {
    keys.forEach((k, i) => {
        let index = arr.findIndex(item => item[k] == value[i])
        arr.splice(index, 1)
    })
}
function demo (list) {
  let keys = [], item;
  for (let a = list.length - 1; a >= 0; a--) {
    item = list[a]
    if(keys.some(t => t === item.topic)) {
      list.splice(a, 1)
    } else {
      keys.push(item.topic)
    }
  }
  return list
}

var arr = [
  {
    name: '张三',
    topic: '班主任'
  },
  {
    name: '李四',
    topic: '体育老师'
  },
  {
    name: '王五',
    topic: '班主任'
  },
  {
    name: '赵六',
    topic: '体育老师'
  }
]
var res = demo(arr)
console.log(JSON.stringify(res)) // => [{"name":"王五","topic":"班主任"},{"name":"赵六","topic":"体育老师"}]

arr.reduce((pre,item)=>{if(!pre.find(iitem=>iitem.topic==item.topic)){pre.push(item)}return pre},[])

let match = cols => (list => (o) => list.filter((c, i) => {
    let r = c.has(o[cols[i]]);
    c.add(o[cols[i]]);
    return r
}).length === 0)(cols.map(() => new Set));

let exec = cols => (match => arr => arr.reduceRight((res, o) => match(o) ? [o, ...res] : res, []))(match(cols))
exec(['topic'])(arr);

clipboard.png

clipboard.png

prevArray.reduce((nextArray,data) => [...nextArray.filter(d => d.topic !== data.topic),data] ,[])

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题