[英]Remove objects from previous array if they don't match the new one
I am trying to remove the values that don't match in the previous array to the values in the new array.我正在尝试将前一个数组中不匹配的值删除到新数组中的值。
var previous = [
{m: "195/50 15"},
{m: "195/50 16"},
{m: "195/55 15"},
{m: "195/55 16"},
{m: "195/55 20"}
];
var newOne = [
{m: "195/55 15"},
{m: "195/55 16"},
{m: "195/55 20"}
];
console.log( previous.filter((obj) => obj['m'] !== newOne['m']) );
And if the new array is empty, then the filter should return an empty array.如果新数组为空,则过滤器应返回一个空数组。
The method I am trying above doesn't work.我上面尝试的方法不起作用。
Try using some to determine if the value is in the other array:尝试使用 some 来确定该值是否在另一个数组中:
var previous = [ {m: "195/50 15"}, {m: "195/50 16"}, {m: "195/55 15"}, {m: "195/55 16"}, {m: "195/55 20"} ]; var newOne = [ {m: "195/55 15"}, {m: "195/55 16"}, {m: "195/55 20"} ]; const result = previous.filter(p => { return newOne.some(n => nm === pm); }) console.log(result);
Comparison should be like this对比应该是这样的
var previous = [
{m: "195/50 15"},
{m: "195/50 16"},
{m: "195/55 15"},
{m: "195/55 16"},
{m: "195/55 20"}
];
var newOne = [
{m: "195/55 15"},
{m: "195/55 16"},
{m: "195/55 20"}
];
console.log( previous.filter((obj, i) => newOne[i] && obj['m'] !== newOne[i]['m']) );
In your code you are using filter function that runs through objects inside previous array and compares each object value with newOne['m'] which returns undefined
在您的代码中,您正在使用过滤器 function 运行前一个数组中的对象并将每个 object 值与返回undefined
的 newOne['m'] 进行比较
let newArray = []
previous.forEach(pobj => {
newOne.forEach(nobj => {
if(pobj['m'] === nobj['m']){
newArray.push(pobj)
}
})
})
console.log(newArray)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.