我正在研究Knockout.js。
var chosenFruit = ko.observableArray([]);
var allFruits = ko.observableArray([]);
allFruits = [ "Apple" , "Bananna" , "Grapes" , "Oranges"]
chosenFruit = ["Apple" , "Bananna" , "kiwi"]
现在,由于First Array中没有“Kiwi”(这意味着,在allFruits中),我想从第二个数组中删除“Kiwi”(selectedFruit)。
我想比较两个数组并从第二个数组中删除 - 第一个数组中不存在的值。
这意味着,在比较之后,第二个数组应该是:
chosenFruit = ["Apple" , "Bananna"]
请建议如何实现这一目标。
提前谢谢你!
答案 0 :(得分:1)
使用 Array#filter
方法
var allFruits = ["Apple", "Bananna", "Grapes", "Oranges"],
chosenFruit = ["Apple", "Bananna", "kiwi"];
console.log(
// iterate and filter out element
chosenFruit.filter(function(v) {
// check value present in array
return allFruits.indexOf(v) > -1;
})
)
更新1:如果您希望保留引用,请使用 Array#splice
删除该元素。
var allFruits = ["Apple", "Bananna", "Grapes", "Oranges"],
chosenFruit = ["Apple", "Bananna", "kiwi"];
// store length for iterating
var i = chosenFruit.length;
// iterate upto `0`
while (i--) {
// check value exist in array
if (allFruits.indexOf(chosenFruit[i]) == -1) {
// if not present then remove it
chosenFruit.splice(i, 1);
}
}
console.log(chosenFruit);
更新2:
使用 Array#filter
生成新的过滤数组时,使用knockout执行此类操作。
var chosenFruit = ko.observableArray(["Apple", "Bananna", "Grapes", "Oranges"]);
var allFruits = ko.observableArray(["Apple", "Bananna", "kiwi"]);
console.log(
chosenFruit().filter(function(v) {
return allFruits().indexOf(v) > -1;
})
)
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
更新3:如果您想更新observableArray,请使用带有回调函数的remove()
方法。
var chosenFruit = ko.observableArray(["Apple", "Bananna", "Grapes", "Oranges"]);
var allFruits = ko.observableArray(["Apple", "Bananna", "kiwi"]);
allFruits.remove(function(v) {
return chosenFruit().indexOf(v) == -1;
});
console.log(allFruits())
<script src="https://cdnjs.cloudflare.com/ajax/libs/knockout/3.2.0/knockout-min.js"></script>
答案 1 :(得分:0)
您可以通过查找和删除不应在chosenFruits
数组中的项目来执行以下操作。
allFruits = [ "Apple" , "Bananna" , "Grapes" , "Oranges"],
chosenFruit = ["Apple" , "Bananna" , "Kiwi", "Melon", "Cockroach"];
discarded = chosenFruit.reduceRight((p,c,i,a) => !allFruits.includes(c) ? p.concat(a.splice(i,1)) : p,[]);
console.log(chosenFruit);
console.log(discarded);
使用传统功能;
allFruits = [ "Apple" , "Bananna" , "Grapes" , "Oranges"],
chosenFruit = ["Apple" , "Bananna" , "Kiwi", "Melon", "Cockroach"];
discarded = chosenFruit.reduceRight(function(p,c,i,a){
return allFruits.indexOf(c) === -1 ? p.concat(a.splice(i,1))
: p;
},[]);
console.log(chosenFruit);
console.log(discarded);
答案 2 :(得分:0)
-DLLVM_EXPERIMENTAL_TARGETS_TO_BUILD=Abc
console.log($(["Apple" , "Bananna" , "kiwi"]).filter([ "Apple" , "Bananna" , "Grapes" , "Oranges"]).get());