I'm trying to compare results from two different arrays containing similar strings;
我试图比较两个包含相似字符串的不同数组的结果;
Array1:
A350.1 - 2h 46 m
A210.2 - 3h 46 m
Array2:
A450.3 - 8h 0 m
A440.5 - 13h 0 m
A450.1 - 4h 0 m
A350.1 - 1h 45 m
A320.7 - 3h 45 m
So I would need to filter out A350.1 - 2h 46 m
from Array1 since there's a similar object A350.1 - 1h 45 m
in Array2
所以我需要从Array1滤出A350.1 - 2h 46米,因为有类似物体A350.1 - 阵列2中1小时45米
The results should look like this from the filtered array, only removing the object which has the identical name (in this example A350.1
):
结果应该从过滤后的数组看起来像这样,只删除具有相同名称的对象(在本例中为A350.1):
A210.2 - 3h 46 m
Any way I could do this effectively and push the results in a new filtered array?
我能以任何方式有效地做到这一点并将结果推送到新的过滤数组中吗?
3 个解决方案
#1
2
try this:
var arr1 = ["A350.1 - 2h 46 m", "A210.2 - 3h 46 m"]
var arr2 = ["A450.3 - 8h 0 m",
"A440.5 - 13h 0 m",
"A450.1 - 4h 0 m",
"A350.1 - 1h 45 m",
"A320.7 - 3h 45 m"
]
var firstPart = [];
arr1.forEach(function(obj1) {
firstPart.push(obj1.substring(0, obj1.indexOf('-')))
});
arr2.forEach(function(obj2) {
var i = firstPart.indexOf(obj2.substring(0, obj2.indexOf('-')));
if (i !== -1)
arr1.splice(i, 1);
});
console.log(arr1)
#2
0
Make a loop that compare each values of Array1 against each values of Array2 and split your string like so array1[i].split("-");
to only compare the first part of your string
创建一个循环,将Array1的每个值与Array2的每个值进行比较,然后拆分字符串,如array1 [i] .split(“ - ”);仅比较字符串的第一部分
#3
0
Prepare your lookup array by splitting off the interesting bit
通过拆分有趣的位来准备查找数组
var arr2_prepared = arr2.map(x => x.split(' - ')[0]);
Then filter out the elements from the data array that do not have the first part of their strings in the lookup array
然后从数据数组中过滤掉在查找数组中没有字符串第一部分的元素
var result = arr1.filter(x => arr2_prepared.indexOf(x.split(' - ')[0]) === -1);
#1
2
try this:
var arr1 = ["A350.1 - 2h 46 m", "A210.2 - 3h 46 m"]
var arr2 = ["A450.3 - 8h 0 m",
"A440.5 - 13h 0 m",
"A450.1 - 4h 0 m",
"A350.1 - 1h 45 m",
"A320.7 - 3h 45 m"
]
var firstPart = [];
arr1.forEach(function(obj1) {
firstPart.push(obj1.substring(0, obj1.indexOf('-')))
});
arr2.forEach(function(obj2) {
var i = firstPart.indexOf(obj2.substring(0, obj2.indexOf('-')));
if (i !== -1)
arr1.splice(i, 1);
});
console.log(arr1)
#2
0
Make a loop that compare each values of Array1 against each values of Array2 and split your string like so array1[i].split("-");
to only compare the first part of your string
创建一个循环,将Array1的每个值与Array2的每个值进行比较,然后拆分字符串,如array1 [i] .split(“ - ”);仅比较字符串的第一部分
#3
0
Prepare your lookup array by splitting off the interesting bit
通过拆分有趣的位来准备查找数组
var arr2_prepared = arr2.map(x => x.split(' - ')[0]);
Then filter out the elements from the data array that do not have the first part of their strings in the lookup array
然后从数据数组中过滤掉在查找数组中没有字符串第一部分的元素
var result = arr1.filter(x => arr2_prepared.indexOf(x.split(' - ')[0]) === -1);