Js按数组对象过滤数组对象

时间:2019-07-26 10:37:09

标签: javascript arrays filter

我有以下数组。

原始数组:

var array =[
  { "id": 1, "name": "abc", "gender": "m","age": "15" },
  { "id": 2, "name": "a", "gender": "m", "age": "25"  },
  { "id": 3,"name": "efg", "gender": "f","age": "5" },
  { "id": 4,"name": "hjk","gender": "m","age": "35" },
  {  "id": 5, "name": "ikly","gender": "m","age": "41" },
  { "id": 6, "name": "ert", "gender": "f", "age": "30" },
  { "id": 7, "name": "qwe", "gender": "f", "age": "31" },
  { "id":8, "name": "bdd",  "gender": "m", "age": " 8" }
];

数组删除:

var arrayCopy =[
  { "id": 1, "name": "abc", "gender": "m","age": "15" },
  { "id": 3,"name": "efg", "gender": "f","age": "5" },
  { "id": 7, "name": "qwe", "gender": "f", "age": "31" },
  { "id":8, "name": "bdd",  "gender": "m", "age": " 8" }
];

我必须删除remove数组中包含的原始数组中的元素,但是我遇到了一些问题。

我考虑过从数组副本中获取所有ID,然后进行排除,但我不确定这是最好的方法。

一些建议?

2 个答案:

答案 0 :(得分:2)

创建一个Set个ID,将其排除在arrayCopy之外。然后,您可以过滤数组,并保留ID中未出现在Set中的所有项目:

const array = [{"id":1,"name":"abc","gender":"m","age":"15"},{"id":2,"name":"a","gender":"m","age":"25"},{"id":3,"name":"efg","gender":"f","age":"5"},{"id":4,"name":"hjk","gender":"m","age":"35"},{"id":5,"name":"ikly","gender":"m","age":"41"},{"id":6,"name":"ert","gender":"f","age":"30"},{"id":7,"name":"qwe","gender":"f","age":"31"},{"id":8,"name":"bdd","gender":"m","age":" 8"}];
const arrayCopy = [{"id":1,"name":"abc","gender":"m","age":"15"},{"id":3,"name":"efg","gender":"f","age":"5"},{"id":7,"name":"qwe","gender":"f","age":"31"},{"id":8,"name":"bdd","gender":"m","age":" 8"}];

const idsToExclude = new Set(arrayCopy.map(({ id }) => id));

const result = array.filter(({ id }) => !idsToExclude.has(id));

console.log(result);

答案 1 :(得分:1)

  

我想从数组副本中获取所有ID,然后进行排除...

是的,那可能是最好的方法。将它们存储在Set(ES2015 +)或对象中作为属性(例如ids[id] = true),然后在原始数组上使用filter,仅保留ID不在条目中的条目。集合/对象。

或者,如果数组很短,则可以在外部数组上使用filter,然后在“删除”数组上使用some,以确定它是否具有外部数组条目的ID。这意味着要反复遍历“删除”数组(对于外部数组中的每个条目一次),但是对于较小的数组来说这不是问题。