ReasonPlay ReasonPlay - 3 months ago 9
Javascript Question

How to skip same values and get array length

I have my example array:

var person = [{
firstName:"John",
lastName:"Doe",
age:46
},
{
firstName:"Alexander",
lastName:"Bru",
age:46
},
{
firstName:"Alex",
lastName:"Bruce",
age:26
}];


Simple
person.length
gives me the length of my array, but I need to merge values when the age is the same. So if two people have same age return
1
no
2
. Sorry for my bad English, I can made a mistakes.

Answer

Use Array#forEach method with an object reference for age.

var person = [{
  firstName: "John",
  lastName: "Doe",
  age: 46
}, {
  firstName: "Alexander",
  lastName: "Bru",
  age: 46
}, {
  firstName: "Alex",
  lastName: "Bruce",
  age: 26
}];
// object for storing reference to age
var obj = {},
  res = 0;
// iterate and count
person.forEach(function(v) {
  // check age already not defined
  if (obj[v.age]) {
    // define the property
    obj[v.age] = true;
    // increment count
    res++;
  }
});

console.log(res);