compare two arrays and get total and matching elements

57 Views Asked by At

I want to get the count of total elements in my array, and the count of elements matching a condition and count of not matching the same condition. The condition is the field name.

Here is list A:

[
{"name": "tom", "id": "1"},
{"name": "jack", "id": "2"},
{"name": "sarah", "id": "3"},
{"name": "william", "id": "4"},
{"name": "ronaldo", "id": "5"}
]

and here is list B:

[
{"name": "tom", "age": "20"},
{"name": "jack", "age": "25"}
]

as a result, it should give out three values:

var total = 5;
var matching = 2;
var notmatchin = 3;

how can this be done with some map and reduce methods in javascript ecma 6?

2

There are 2 best solutions below

0
On BEST ANSWER
  • Get the full count with a.length
  • Get the matching count by using b.reduce to accumulate a count where the current .name is found in a. Do this by using .some(), which returns true or false. Since booleans are converted to 1 and 0 respectively, you can simply add them to the accumulator.
  • Get the non-matching by subtracting the matching from the full count.

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

1
On

You can use .length to check the count

You can use .reduce to count the matches. Can use .includes to check if string is in array.

Getting not matches by simple arithmetic.

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

For more info about reduce: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce