[英]Javascript arrays of Objects; Subtract one from another
Put simply, I want to subtract one array from another.简单地说,我想从另一个数组中减去一个数组。
The arrays are arrays of objects.数组是对象的数组。 I understand I can cycle through one array and on each item, comparing values in the other array, but that just seems a little messy.
我知道我可以循环遍历一个数组和每个项目,比较另一个数组中的值,但这似乎有点混乱。
Thanks for the help, hopefully this question isnt too basic, I have tried googling it with no luck :(感谢您的帮助,希望这个问题不是太基本,我试过用谷歌搜索它但没有运气:(
EDIT:编辑:
The Objects in the Arrays I wish to remove will have identical values but are NOT the same object (thanks @patrick dw).我希望删除的数组中的对象将具有相同的值但不是相同的对象(感谢@patrick dw)。 I am looking to completely remove the subset from the initial array.
我希望从初始数组中完全删除子集。
This answer is copied from https://stackoverflow.com/a/53092728/7173655 , extended with a comment and a solution with objects.这个答案是从https://stackoverflow.com/a/53092728/7173655复制的,扩展了评论和对象解决方案。
The code filters array A. All values included in B are removed from A.代码过滤器数组 A。 B 中包含的所有值都从 A 中删除。
const A = [1, 4, 3, 2] const B = [0, 2, 1, 2] console.log(A.filter(n => !B.includes(n)))
The same with objects:对象也一样:
const A = [{id:1}, {id:4}, {id:3}, {id:2}] const B = [{id:0}, {id:2}, {id:1}, {id:2}] console.log(A.filter(a => !B.map(b=>b.id).includes(a.id)))
http://phpjs.org/functions/index http://phpjs.org/functions/index
There is no built-in method to do this in JavaScript. JavaScript 中没有内置方法可以做到这一点。 If you look at this site there are a lot of functions for arrays with similar syntax to PHP.
如果您查看此站点,则有很多用于数组的函数与 PHP 的语法相似。
http://www.jslab.dk/library/Array http://www.jslab.dk/library/Array
This site has some js functions on "sets"这个站点有一些关于“sets”的js函数
I think you need the diff function.我认为您需要 diff 功能。
It should remove all values from list a, which are present in list b keeping their order.它应该从列表 a 中删除所有值,这些值出现在列表 b 中并保持它们的顺序。
let a = [0, 2, 5, 6, 1];
let b = [2, 6, 2, 5, 0];
function arrayDiff() {
for (i of b) {
for (j of a) {
if (i === j) {
a.splice(a.indexOf(j), 1);
}
}
}
return a;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.