我想得到数组中总元素的数量,以及匹配条件的元素数和不匹配相同条件的数量。 条件是字段名称。
这是列表A:
[
{"name": "tom", "id": "1"},
{"name": "jack", "id": "2"},
{"name": "sarah", "id": "3"},
{"name": "william", "id": "4"},
{"name": "ronaldo", "id": "5"}
]
,这是列表B:
[
{"name": "tom", "age": "20"},
{"name": "jack", "age": "25"}
]
因此,它应该给出三个值:
var total = 5;
var matching = 2;
var notmatchin = 3;
如何通过javascript ecma 6中的一些map和reduce方法来完成?
答案 0 :(得分:1)
您可以使用.length
来检查点数
您可以使用.reduce
来计算匹配数。可以使用.includes
来检查字符串是否在数组中。
通过简单算术获得不匹配。
var $arr1 = [{
"name": "tom",
"id": "1"
},
{
"name": "jack",
"id": "2"
},
{
"name": "sarah",
"id": "3"
},
{
"name": "william",
"id": "4"
},
{
"name": "ronaldo",
"id": "5"
}
];
var $arr2 = [{
"name": "tom",
"age": "20"
},
{
"name": "jack",
"age": "25"
}
]
//Make temp array of $arr2
var temp = $arr2.map((v) => v.name);
//Get count
var count = $arr1.length;
//Get match using reduce
var match = $arr1.reduce((c, i) => {
temp.includes(i.name) ? c++ : c;
return c;
}, 0);
//Get unmatch
var unmatch = count - match;
console.log("Count " + count);
console.log("Match " + match);
console.log("Not Match " + unmatch);
有关reduce:https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
的更多信息答案 1 :(得分:1)
a.length
b.reduce
累积在.name
中找到当前a
的计数,以获取匹配计数。使用.some()
执行此操作,返回true
或false
。由于布尔值分别转换为1
和0
,您只需将它们添加到累加器即可。
var a = [
{"name": "tom", "id": "1"},
{"name": "jack", "id": "2"},
{"name": "sarah", "id": "3"},
{"name": "william", "id": "4"},
{"name": "ronaldo", "id": "5"}
];
var b = [
{"name": "tom", "age": "20"},
{"name": "jack", "age": "25"}
];
var total = a.length;
var matching = b.reduce((n, o) => n + (a.some(oo => o.name == oo.name)), 0);
var notmatching = total - matching;
console.log(`total: ${total}
match: ${matching}
no match: ${notmatching}`);