比较两个数组并获得总数和匹配元素

时间:2018-02-11 15:34:26

标签: javascript arrays ecmascript-6

我想得到数组中总元素的数量,以及匹配条件的元素数和不匹配相同条件的数量。 条件是字段名称

这是列表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方法来完成?

2 个答案:

答案 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()执行此操作,返回truefalse。由于布尔值分别转换为10,您只需将它们添加到累加器即可。
  • 通过从完整计数中减去匹配来获得不匹配。

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}`);