我想找到两个数组之间的匹配值,并创建一个json数组,如果值匹配则设置为true,否则将设置为false。我知道,secondaryArray中的值将始终与第一个数组中的某些值匹配,并且将始终较小,因为secondArray是基于第一个数组创建的。
let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];
我想创建一个json数组:
[
{
"name": "One",
"matched": false
},
{
"name": "Two",
"matched": false
},
{
"name": "Three",
"matched": true
},
{
"name": "Four",
"matched": true
},
{
"name": "Five",
"matched": false
}
]
通常,我会这样做:
firstArray.forEach(firstElement=>{
secondArray.forEach(secondElement=>{
if(firstArray.indexOf(secondElement)>=0){
jsonArray.push({'name': secondElement, 'matched': true});
}else{
jsonArray.push({'name': secondElement, 'matched': false});
}
});
});
但这只会创建一个具有重复值的json数组,其中名称相同,但是匹配的值是false和true。
似乎我迷失在一个非常简单的事情中。
答案 0 :(得分:1)
这里所有其他解决方案都执行不必要的计算;它们的运行时间与数组长度的平方成正比。尝试使用大小为100k +的数组运行它们:-)
您要寻找的解决方案非常简单,并且可以在O(n)
中运行:
let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let map = {};
firstArray.forEach(i => map[i] = false);
secondArray.forEach(i => map[i] === false && (map[i] = true));
let jsonArray = Object.keys(map).map(k => ({ name: k, matched: map[k] }));
答案 1 :(得分:0)
使用find
检查元素是否存在
firstArray.forEach(secondElement=>{
let exist = secondArray.find((item) => item === secondElement);
if(exist){
jsonArray.push({'name': secondElement, 'matched': true})
}else{
jsonArray.push({'name': secondElement, 'matched': false})
}
});
答案 2 :(得分:0)
尝试一下:
let firstArray = ["One", "Two", "Three". "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];
firstArray.forEach(firstElement=>{
if(secondArray.indexOf(firstElement)>=0){
jsonArray.push({'name': firstElement, 'matched': true});
}else{
jsonArray.push({'name': firstElement, 'matched': false});
}
});
希望此代码对您有帮助
答案 3 :(得分:0)
我们可以使用
Array.prototype.includes()
检查数组中是否存在元素
let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];
firstArray.forEach(val=>{
if(secondArray.includes(val))
{
jsonArray.push({'name': val, 'matched': true})
}else{
jsonArray.push({'name': val, 'matched': false})
}
})
console.log(jsonArray);
答案 4 :(得分:0)
您可以结合使用map
和includes
助手来实现这一目标。
let firstArray = ["One", "Two", "Three", "Four", "Five"];
let secondArray = ["Three", "Four"];
let jsonArray = [];
jsonArray = firstArray.map(i => {
return { 'name': i, 'matched': secondArray.includes(i) };
});
console.log(jsonArray);
答案 5 :(得分:0)
您可以通过两种方式进行操作。
Way1:
let array1 = ['a','b','c','d'];
let array2 = ['b','d'];
let commonArray = [];
array1.forEach( x => {
if(array2.indexOf(x) != -1){
commonArray.push(x);
}
});`
console.log(commonArray); //commonArray is the resulting array
Way2: Use intersection of Underscore.js
At first you have to import underscore:
import * as _ from 'underscore';`
Then use intersection to calculate common.
commonArray = _.intersection(array1, array2);
console.log(commonArray); //commonArray is the resulting array