如何获取数组中的不同对象:Javascript
how to fetch distinct objects in array : Javascript
我正在尝试从可能具有重复对象的数组中获取唯一对象。我已经尝试了新的 Set 和新的 Map 但我仍然没有得到我的结果。
例如我有以下对象数组
const myArray = [{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
console.log([...new Set(myArray.map((item) => item.x && item.y ))]) // [22, 23]
当我想要这个时
[{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
它应该删除 myArray 中的第四个对象,因为它在重复
你的map
returns如下
myArray.map((item) => item.x && item.y) // [ 22, 22, 22, 22, 23 ]
因为它首先检查 item.x
是否为 truthy
。因为它 true
总是所以它 returns value
在 &&
之后
并且当您应用 set
时,它将从数组
中过滤唯一值
[...new Set(myArray.map((item) => item.x && item.y))] // [ 22, 23 ]
替代方法
const myArray = [
{ x: 10, y: 22 },
{ x: 11, y: 22 },
{ x: 12, y: 22 },
{ x: 12, y: 22 },
{ x: 12, y: 23 },
];
const strArray = myArray.map(({ x, y }) => `${x}/${y}`);
const str = [...new Set(strArray)];
const result = str.map((str) => {
const [x, y] = str.split("/");
return { x, y };
});
console.log(result);
你可以使用 reduce 和一些:
const myArray = [{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
const Filtered = [];
const filterDuplicates = myArray.reduce((arr, el) => {
if(!arr.some(current => current.x === el.x && current.y === el.y)) {
arr.push(el);
}
return arr;
}, Filtered);
console.log(Filtered);
我正在尝试从可能具有重复对象的数组中获取唯一对象。我已经尝试了新的 Set 和新的 Map 但我仍然没有得到我的结果。
例如我有以下对象数组
const myArray = [{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
console.log([...new Set(myArray.map((item) => item.x && item.y ))]) // [22, 23]
当我想要这个时
[{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
它应该删除 myArray 中的第四个对象,因为它在重复
你的map
returns如下
myArray.map((item) => item.x && item.y) // [ 22, 22, 22, 22, 23 ]
因为它首先检查 item.x
是否为 truthy
。因为它 true
总是所以它 returns value
在 &&
并且当您应用 set
时,它将从数组
[...new Set(myArray.map((item) => item.x && item.y))] // [ 22, 23 ]
替代方法
const myArray = [
{ x: 10, y: 22 },
{ x: 11, y: 22 },
{ x: 12, y: 22 },
{ x: 12, y: 22 },
{ x: 12, y: 23 },
];
const strArray = myArray.map(({ x, y }) => `${x}/${y}`);
const str = [...new Set(strArray)];
const result = str.map((str) => {
const [x, y] = str.split("/");
return { x, y };
});
console.log(result);
你可以使用 reduce 和一些:
const myArray = [{ x: 10, y: 22}, { x: 11, y: 22}, { x: 12, y: 22}, { x: 12, y: 22}, { x: 12, y: 23}];
const Filtered = [];
const filterDuplicates = myArray.reduce((arr, el) => {
if(!arr.some(current => current.x === el.x && current.y === el.y)) {
arr.push(el);
}
return arr;
}, Filtered);
console.log(Filtered);