![](/img/trans.png)
[英]Create a function that returns an array with unique items built from two arrays or an array and multiple single items
[英]function to remove single items or arrays from within an array - javascript
我有一个包含一些单项和一些数组的数组:
var groceries = ["toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish"];
我想编写一个函数,以在调用时删除其中的某些项或数组。
对于单个项目,我编写了以下函数:
function removeItems(arr, item) {
for ( var i = 0; i < item.length; i++ ) {
var index = arr.indexOf(item[i]);
if (index > -1) {
arr.splice(index, 1);
}
}
};
所以我可以打电话给:
removeItems(groceries, ["fish", "orange juice"]);
这完全符合我的要求。 但是,我不知道如何使函数也能够从较大的数组中删除数组(例如[“ chocolate”,“ ice cream”])。 我将如何处理?
使用Array#reduce创建密钥字典。 如果该项是数组,则将所有值连接起来以创建键。 然后,通过生成相同的键并根据字典检查它们来过滤所有项目。
注意-Array#filter会创建一个新数组,并且不会更改原始数组。
var groceries = ["toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish"]; function removeItems(arr, toRemove) { function createKey(item) { return Array.isArray(item) ? item.join('-') : item; } var removeDict = toRemove.reduce(function(d, item) { var key = createKey(item); d[key] = true; return d; }, {}); return arr.filter(function(item) { var key = createKey(item); return !removeDict[key]; }); } var result = removeItems(groceries, ["fish", "orange juice", ["chocolate", "ice cream"]]); console.log(result);
在诸如从主题中删除元素之类的问题中,我倾向于远离使用函数数组方法,因为即使您开始删除项目,它们也会根据初始项目计数进行迭代。 因此,我的解决方案势在必行。
function remover(itemToDelete, items){ var i = 0, check = false; for (var item of items){ check = Array.isArray(item) ? item.includes(itemToDelete) : item === itemToDelete; check ? items.splice(i,1) : i++; } return items; } var groceries = ["toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish"]; console.log(remover("chocolate", groceries)); console.log(remover("fish", groceries));
这就是我要做的:
const groceries = [ "toothpaste", ["plums", "peaches", "pineapples"], ["carrots", "corn", "green beans"], "orange juice", ["chocolate", "ice cream"], "paper towels", "fish" ]; const equals = (x, y) => JSON.stringify(x) === JSON.stringify(y); const removeItems = (xs, ys) => xs.filter(x => !ys.some(y => equals(x, y))); const result = removeItems(groceries, [ "fish", "orange juice", ["chocolate", "ice cream"] ]); console.log(result);
首先,我们定义两个值相等意味着什么。 接下来,我们使用此值相等性定义removeItems
。 我们说把所有的x
这不等于任何y
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.