减去数组 - javascript
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21509474/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Subtract arrays - javascript
提问by bsaglamtimur
I have arrays like;
我有像这样的数组;
var john = { name: "John Smith", age: 23 };
var mary = { name: "Mary Key", age: 18 };
var bob = { name: "Bob-small", age: 6 };
var people = [john, mary, bob];
var john2 = { name: "John Smith", age: 23 };
var people2 = [john2];
What I would like to do is subtract people2 from people and get result;
我想做的是从 people 中减去 people2 并得到结果;
[mary, bob];
How can I achieve this? TIA
我怎样才能做到这一点?TIA
回答by Aadit M Shah
The first thing you need is a way to compare two people for mathematical equivalence. We cannot use the ===
operator because it tests two objects for identity equivalence, not mathematical equivalence. For example:
您需要的第一件事是比较两个人的数学等价性的方法。我们不能使用===
运算符,因为它测试两个对象的身份等价,而不是数学等价。例如:
var john = {name: "John Smith", age: 23};
var john2 = {name: "John Smith", age: 23};
console.log(john === john2); // false
Hence we create a function to compare two people:
因此,我们创建了一个函数来比较两个人:
console.log(similarPeople(john, john2));
function similarPeople(a, b) {
return a.name === b.name &&
a.age === b.age;
}
The reason the function is named similarPeople
and not samePeople
is because two different people may have the same name and may be of the same age.
函数被命名similarPeople
而不是命名的原因samePeople
是因为两个不同的人可能有相同的名字并且可能年龄相同。
The difference of two sets, A and B, is defined as the set of all those elements of A which are not in B.
两个集合 A 和 B 的差被定义为 A 中所有不在 B 中的元素的集合。
At worst computing the set difference of two sets, A and B, of sizes m
and n
respectively would take O(m * n)
time. Not very efficient:
在最坏的情况计算的两组,A和B,尺寸的差集m
和n
分别将采取O(m * n)
时间。效率不高:
function difference(a, b, eq) {
if (arguments.length < 3) eq = function (a, b) {
return a === b;
};
var m = a.length;
var n = b.length;
var c = [];
loop: for (var i = 0; i < m; i++) {
var x = a[i];
for (var j = 0; j < n; j++)
if (eq(b[j], x))
continue loop;
c.push(x);
}
return c;
}
Now you could get the difference of two lists of people as follows:
现在你可以得到两个人列表的差异,如下所示:
var people = [john, mary, bob];
var people2 = [john2];
console.log(difference(people, people2, similarPeople)); // [mary, bob]
See the demo: http://jsfiddle.net/F7RDs/
看演示:http: //jsfiddle.net/F7RDs/
Fortunately there's a faster way to compute the set difference for large sets: indices. Let's create a function to create an index of a list of people:
幸运的是,有一种更快的方法来计算大集合的集合差:索引。让我们创建一个函数来创建人员列表的索引:
function indexFrom(people) {
var length = people.length, index = {};
for (var i = 0; i < length; i++) {
var person = people[i];
var name = person.name;
if (index.hasOwnProperty(name)) var subindex = index[name];
else var subindex = index[name] = {};
subindex[person.age] = {};
}
return index;
}
Now we create an index for the second list of people:
现在我们为第二个人员列表创建一个索引:
var index2 = indexFrom(people2);
We also need a function to test whether a person is in a list using its index:
我们还需要一个函数来使用它的索引来测试一个人是否在列表中:
function hasPerson(person, index) {
var name = person.name;
return index.hasOwnProperty(name) &&
index[name].hasOwnProperty(person.age);
}
Finally we can create a more efficient implementation of difference
as follows:
最后,我们可以创建一个更有效的实现,difference
如下所示:
function difference(a, index, has) {
var m = a.length, c = [];
for (var i = 0; i < m; i++) {
var x = a[i];
if (!has(x, index))
c.push(x);
}
return c;
}
You use it as follows:
您可以按如下方式使用它:
console.log(difference(people, index2, hasPerson)); // [mary, bob]
The advantage is that creating an index takes O(n)
time and calculating the difference takes O(m)
time. Hence in total it only takes O(m + n)
time instead of O(m * n)
time. In addition you can cache the index for future use.
优点是创建索引需要O(n)
时间,计算差异需要O(m)
时间。因此,总的来说它只需要O(m + n)
时间而不是O(m * n)
时间。此外,您可以缓存索引以备将来使用。
See the demo: http://jsfiddle.net/F7RDs/1/
看演示:http: //jsfiddle.net/F7RDs/1/
Hope this helped.
希望这有帮助。
回答by Tibos
Here is an easy solution:
这是一个简单的解决方案:
var diff = people.filter(function(item) {
return !people2.some(function(test){
return test.name === item.name && test.age === item.age;
});
});
Make sure the function passed to people2.some
correctly checks that the two objects are equal, since ==
would fail, as you have references to different objects with identical properties.
确保传递给的函数people2.some
正确检查两个对象是否相等,因为==
会失败,因为您引用了具有相同属性的不同对象。
回答by user2804021
So, here goes the final running code. Copy , paste it and check for the output.It is first of all separating the strings (comma-separation). Then it is comparing them individually . Check this link: http://jsfiddle.net/DXRZ4/
所以,这是最终的运行代码。复制、粘贴并检查输出。首先是分隔字符串(逗号分隔)。然后是单独比较它们。检查此链接:http: //jsfiddle.net/DXRZ4/
<html>
<head>
<script>
var a = new Array(); var i=1; var people = new Array();
function fun() {
var str = "john,john,bob",
l = str.split(",");
for(i=0; i<3; i++) {
a[i] = l[i];
// this will show the comma separated strings
document.writeln(l[i]);
}
for(i=0; i<3; i++) {
t=a[i];
j=a[i+1];
if((a[i]==a[i+1]) || (a[i]==a[i+2])) {
// it will store the position of string which are same
p=i;
}
}
for(i=0; i<3; i++) {
if(p!=i){
document.writeln("Subtracted Strings are:-");
document.writeln(l[i]);
}
}
}
</script>
<body>
<input type="button" name="b1" onClick="fun()">
</body>
</html>