gpt4 book ai didi

javascript - 如何在 Javascript 中删除数组中的重复数组?

转载 作者:行者123 更新时间:2023-11-29 15:58:50 26 4
gpt4 key购买 nike

如何在 Javascript 中删除重复的排序数组?我尝试制作一个新数组,在新集合上使用扩展语法,但这看起来非常复杂,并迫使我的结果集看起来像这样:

[ [ '-', '1', ',', '0', ',', '1' ],
[ '-', '1', ',', '-', '1', ',', '2' ] ]
[ [ '-', '1', ',', '0', ',', '1' ],
[ '-', '1', ',', '-', '1', ',', '2' ] ]
[ [ '0', ',', '0', ',', '0' ] ]
[ [ '0', ',', '0', ',', '0' ] ]
[ [ '-', '4', ',', '-', '2', ',', '6' ],
[ '-', '4', ',', '0', ',', '4' ],
[ '-', '4', ',', '1', ',', '3' ],
[ '-', '4', ',', '2', ',', '2' ],
[ '-', '2', ',', '-', '2', ',', '4' ],
[ '-', '2', ',', '0', ',', '2' ] ]
[ [ '-', '4', ',', '-', '2', ',', '6' ],
[ '-', '4', ',', '0', ',', '4' ],
[ '-', '4', ',', '1', ',', '3' ],
[ '-', '4', ',', '2', ',', '2' ],
[ '-', '2', ',', '-', '2', ',', '4' ],
[ '-', '2', ',', '0', ',', '2' ] ]

[ [ '-1,0,1' ], [ '-1,-1,2' ] ]
[ [ '-1,0,1' ], [ '-1,-1,2' ] ]
[ [ '0,0,0' ] ]
[ [ '0,0,0' ] ]
[ [ '-4,-2,6' ],
[ '-4,0,4' ],
[ '-4,1,3' ],
[ '-4,2,2' ],
[ '-2,-2,4' ],
[ '-2,0,2' ] ]
[ [ '-4,-2,6' ],
[ '-4,0,4' ],
[ '-4,1,3' ],
[ '-4,2,2' ],
[ '-2,-2,4' ],
[ '-2,0,2' ] ]

请注意,这些是在我将它们设置为字符串之后。该集合不会删除重复的排序数组,因为它们是不同的对象。

这是代码。

var threeSum = function (arr) {
let map = new Map();
for (let i = 0; i < arr.length; i++) {
let num = arr[i];
if (map.has(num)) {
map.get(num).push(i);
}
else {
map.set(num, [i]);
}
}

const results = [];
for (let i = 0; i < arr.length; i++) {
for (let j = i + 1; j < arr.length; j++) {
let diff = (arr[i] + arr[j]);
diff = (diff == 0) ? diff: diff * -1;
if (map.has(diff)) {
let mArr = map.get(diff);
for (let k = 0; k < mArr.length; k++) {
if (mArr[k] != i && mArr[k] != j ) {
results.push([arr[i], arr[j], diff]);
}
}
}
}
}

results.forEach((value) => {
value.sort((a, b) => { return a - b });
});
let newResults = results.filter((val, idx, arr) => {
/// how do i do this
})

console.log(newResults);
return newResults;

}

console.log(threeSum([-1, 0, 1, 2, -1, -4]));
console.log(threeSum([0,0,0,0]));
console.log(threeSum([-4,-2,-2,-2,0,1,2,2,2,3,3,4,4,6,6]));

最佳答案

A set 非常适合这项任务。集合保持其所有元素都是唯一的条件。这是您完成任务的方法:

  1. 创建一个包含结果元素的新集合:let set = new Set(results.map(result => JSON.stringify(result))
  2. 将集合转换为数组。这可以使用 Array.from(set).map(elem => JSON.parse(elem))
  3. 来完成

关于javascript - 如何在 Javascript 中删除数组中的重复数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55564391/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com