根据JavaScript中属性的值从对象数组中删除重复项

ffdz8vbo  于 2023-04-04  发布在  Java
关注(0)|答案(5)|浏览(149)

我如何从一个数组someArray中删除重复的元素,就像下面基于name属性给出的条件,如果name对于两个元素是相同的,但对于其中一个元素,typenew,原始的一个(没有类型new)将被保留?
someArray = [{id: 1, name:"apple"}, {id: 2, name:"mango"}, {id: 3, name:"apple", type: "new"}, {id: 4, name:"orange"}, {id: 5, name:"orange", type: "new"}, {id: 6, name: "pineapple", type: "new"}]

[{id: 1, name:"apple"}, {id: 2, name: "mango"}, {id: 4, name:"orange"}, {id: 6, name: "pineapple", type: "new"}]

ghg1uchk

ghg1uchk1#

您可以使用Map来按名称club值,如果有两个同名的值,只需使用没有type = "new"的值

let someArray = [{id: 3, name:"apple", type: "new"}, {id: 1, name:"apple"}, {id: 2, name:"mango"}, {id: 4, name:"orange"}, {id: 5, name:"orange", type: "new"}, {id: 6, name: "pineapple", type: "new"}]

function getUnique(arr){
  let mapObj = new Map()
  
  arr.forEach(v => {
    let prevValue = mapObj.get(v.name)
    if(!prevValue || prevValue.type === "new"){
      mapObj.set(v.name, v)
    } 
  })
  return [...mapObj.values()]
}

console.log(getUnique(someArray))
4ioopgfo

4ioopgfo2#

您可以使用Array.prototype.reduce并筛选出满足条件的项。

const 
  input = [
    { id: 1, name: "apple" },
    { id: 2, name: "mango" },
    { id: 3, name: "apple", type: "new" },
    { id: 4, name: "orange" },
    { id: 5, name: "orange", type: "new" },
    { id: 6, name: "pineapple", type: "new" },
  ],
  output = Object.values(
    input.reduce((r, o) => {
      if (!r[o.name] || (r[o.name].type === "new" && o.type !== "new")) {
        r[o.name] = o;
      }
      return r;
    }, {})
  );

console.log(output);

你也可以使用Spread Syntax

const 
  input = [
    { id: 1, name: "apple" },
    { id: 2, name: "mango" },
    { id: 3, name: "apple", type: "new" },
    { id: 4, name: "orange" },
    { id: 5, name: "orange", type: "new" },
    { id: 6, name: "pineapple", type: "new" },
  ],
  output = Object.values(
    input.reduce(
      (r, o) =>
        !r[o.name] || (r[o.name].type === "new" && o.type !== "new")
          ? { ...r, [o.name]: o }
          : r,
      {}
    )
  );

console.log(output);
nkoocmlb

nkoocmlb3#

你可以迭代你的数组并计算是否是'type:new'并且不存在,则弹出该项。

let someArray = [{
    id: 1,
    name: "apple"
}, {
    id: 2,
    name: "mango"
}, {
    id: 3,
    name: "apple",
    type: "new"
}, {
    id: 4,
    name: "orange"
}, {
    id: 5,
    name: "orange",
    type: "new"
}, {
    id: 6,
    name: "pineapple",
    type: "new"
}];
console.info('Initial value:' + JSON.stringify(someArray));
someArray.forEach(function(item, index, object) {
    if (item.type === 'new' && someArray.filter(val => val.name === item.name && !val.type)) {
        object.splice(index, 1);
    }
});

console.info('Desired Result:' + JSON.stringify(someArray));
iqih9akk

iqih9akk4#

let someArray = [{id: 1, name:"apple"}, {id: 2, name:"mango"}, {id: 3, name:"apple", type: "new"}, {id: 4, name:"orange"}, {id: 5, name:"orange", type: "new"}, {id: 6, name: "pineapple", type: "new"}]
someArray.sort(function (a, b) {
  if (a.type !== 'undefined') return 1
  return 0
})
const result = someArray.reduce((resArr, currentArr) => {
  let other = resArr.some((ele) => currentArr.name === ele.name)
  if (!other) resArr.push(currentArr)
  return resArr
}, [])
console.log(result)
pbossiut

pbossiut5#

要从对象数组中删除重复项,请执行以下操作:
1.创建一个用于存储唯一对象ID的空数组。
1.使用Array.filter()方法过滤对象数组。
1.在新阵列中仅包括具有唯一ID的对象。

// ✅ If you need to check for uniqueness based on a single property
const arr = [
  {id: 1, name: 'Tom'},
  {id: 1, name: 'Tom'},
  {id: 2, name: 'Nick'},
  {id: 2, name: 'Nick'},
];

const uniqueIds = [];

const unique = arr.filter(element => {
  const isDuplicate = uniqueIds.includes(element.id);

  if (!isDuplicate) {
    uniqueIds.push(element.id);

    return true;
  }

  return false;
});

// 👇️ [{id: 1, name: 'Tom'}, {id: 2, name: 'Nick'}]
console.log(unique);

// ------------------------------------------------------------
// ------------------------------------------------------------
// ------------------------------------------------------------

// ✅ If you need to check for uniqueness based on multiple properties

const arr2 = [
  {id: 1, name: 'Tom'},
  {id: 1, name: 'Tom'},
  {id: 1, name: 'Alice'},
  {id: 2, name: 'Nick'},
  {id: 2, name: 'Nick'},
  {id: 2, name: 'Bob'},
];

const unique2 = arr2.filter((obj, index) => {
  return index === arr2.findIndex(o => obj.id === o.id && obj.name === o.name);
});

// [
//   { id: 1, name: 'Tom' },
//   { id: 1, name: 'Alice' },
//   { id: 2, name: 'Nick' },
//   { id: 2, name: 'Bob' }
// ]
console.log(unique2);

相关问题