Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 420
Maciej916 Avatar asked May 09 '26 16:05

Maciej916


1 Answers

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);
like image 119
Pranav C Balan Avatar answered May 12 '26 06:05

Pranav C Balan