3

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.

4 Answers 4

2

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

Sign up to request clarification or add additional context in comments.

1 Comment

@ReasonPlay : glad to help you :)
2

you can use underscore or similar library that supports groupBy:

_.size(_.groupBy(person, "age"))

1 Comment

I don't wanna use additional library but thanks for help.
0

Filter the array down to only those elements for which a find on the array for the first element with the same age yields the element itself, then take the length of the result:

array.filter(o1 => o1 === array.find(o2 => o2.age === o1.age)).length

Another idea involves using a little function called uniqueCount, which counts the number of unique values in a (sorted) array:

function uniqueCount(a) {
  return a.reduce((cnt, elt, i) => a[i] === a[i-1] ? cnt : cnt + 1), 0);
}

Now you can create an array of all the ages, and do a count of its unique elements on it:

uniqueCount(array.map(e => e.age).sort(numeric))

Comments

0

If you are allowed to, you could add all the ages to a set and take its size.

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

const ages = new Set(people.map(person => person.age));
console.log(ages.size)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.