[英]javascript algorithm - returning elements in first array which are not present in second
Hi I am stuck on this algorithm.嗨,我被困在这个算法上。
Can anyone see why this is not working for all tests:谁能看出为什么这不适用于所有测试:
Instructions: Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.说明:你在这个 kata 中的目标是实现一个差异函数,它从另一个列表中减去一个列表并返回结果。 It should remove all values from list a, which are present in list b.
它应该从列表 a 中删除所有存在于列表 b 中的值。
my attempt:我的尝试:
function arrayDiff(a, b) {
for(let i = 0; i < a.length; i++){
for(let j = 0; j < b.length; j++){
if(a[i] === b[j]){
a.splice(i,1 );
}
}
}
return a;
}
When i pass this to my function it works:当我将它传递给我的函数时,它会起作用:
arrayDiff([1,8,2], [])
it passes and returns []
arrayDiff([1,8,2], [])
它通过并返回[]
When i pass this it fails:当我通过它时它失败了:
arrayDiff([1,2,2], [2])
it fails and returns [1, 2]
it should only return [1] arrayDiff([1,2,2], [2])
它失败并返回[1, 2]
它应该只返回 [1]
UPDATE * THIS IS THE QUESTION, not sure if that helps?更新* 这是问题,不确定这是否有帮助?
Your goal in this kata is to implement a difference function, which subtracts one list from another and returns the result.你在这个 kata 中的目标是实现一个差异函数,它从另一个列表中减去一个列表并返回结果。
It should remove all values from list a, which are present in list b.它应该从列表 a 中删除所有存在于列表 b 中的值。
arrayDiff([1,2],[1]) == [2] If a value is present in b, all of its occurrences must be removed from the other: arrayDiff([1,2],[1]) == [2] 如果 b 中存在一个值,则必须从另一个中删除它的所有出现:
arrayDiff([1,2,2,2,3],[2]) == [1,3] arrayDiff([1,2,2,2,3],[2]) == [1,3]
You need to decrement i
after splicing the array, since the array got one shorter.您需要在拼接数组后递减
i
,因为数组变短了。
function arrayDiff(a, b) {
for (let i = 0; i < a.length; i++) {
for (let j = 0; j < b.length; j++) {
if (a[i] === b[j]) {
a.splice(i, 1);
i--;
}
}
}
return a;
}
Edit: that said, a much more elegant solution to this problem would be to solve it functionally.编辑:也就是说,这个问题的一个更优雅的解决方案是从功能上解决它。
function arrayDiff(a, b) {
return a.filter(elem => !b.includes(elem))
}
You can try using Array.Filter method.您可以尝试使用 Array.Filter 方法。
function arrayDiff(a, b) {
return a.filter(value => !b.includes(value));
}
with one for loop带一个 for 循环
function arrayDiff(a, b) {
for (let i = 0; i < a.length; i++) {
if(b.indexOf(a[i]) !== -1) {
a.splice(i, 1);
i--
}
}
return a
}
simple way简单的方法
function arrayDiff(a, b) {
return a.filter(item => b.indexOf(item) === -1);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.