0

I'm trying to write a function that takes as a parameter an array of objects, like this: function getOldest([{name:john, age:69}, {name:jane, age:28}, {name:paul, age: 19}])

The function would check the age property of the objects and find the largest value, and then return the name property.

getOldest([{name: john, age: 35}, {name: jane, age: 20}, {...}])
returns "john"

Additionally, if two key value pairs share the same value, as in two people have the same age, it would return an array instead.

getOldest([{name: john, age: 20}, {name: jane, age: 20}, {...}])
returns ['john', 'jane']

I've been trying to figure out how to do this for about five hours now but I just can't figure it out.

5
  • So tell us, how does your function getOldest() look... Commented Dec 20, 2017 at 6:20
  • trying to write a function - so far you've written the name of a function ... keep trying Commented Dec 20, 2017 at 6:21
  • Sort the array in desc order get the first element. Commented Dec 20, 2017 at 6:22
  • @JaromandaX funny. I tried looping through the array using a for loop selecting the values of age with person[i].age and then an if statement that would go through the values, adding the largest one to an empty variable but that didn't work since I couldn't link that back to the object. Took me a few tries with different versions before I realized I don't know enough to write the code I want. Commented Dec 20, 2017 at 6:37
  • the answer is tow use array reduce - this should be as much of an answer as you get, as you've shown zero effort Commented Dec 20, 2017 at 6:38

5 Answers 5

1

I would always return an array to keep consistency:

 function getOldest(arr){
   const old = arr.reduce((acc, {age}) => Math.max(acc, age), 0);
   return arr.filter(({age}) => age === old);
 }

At first it goes through the array with reduce and finds the oldest age, then it returns the array filtered by that.


If you want to reduce in one step:

 function getOldest(arr){
   var old = 0;
   return arr.reduce((arr, {name, age}) => {
     if(age > old){
       old = age;
       return [name];
     }
     if(age === old) return arr.concat(name);
     return arr;
  }, []);
 }
Sign up to request clarification or add additional context in comments.

6 Comments

Why not post it here as a runnable snippet? You shouldn't need filter, just make the accumulator from the appropriate names.
@robG cause the <> button is disabled on mobile devices ;/
You're keen… I don't bother on my iPhone 5. ;-)
@robg added reducing in one step however thats slightly more convoluted on my opinoon ;)
@gurvinder thanks for pointing out, fixed it ;)
|
0

Use sort, then filter and finally map

var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
arr.sort( ( a, b ) => b.age - b.age ); //sort by age in reverse
var maxAge = arr[ 0 ].age; //find max age
var output  = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name

Demo

var arr = [{
  name: "john",
  age: 69
}, {
  name: "jane",
  age: 28
}, {
  name: "paul",
  age: 19
}];
arr.sort((a, b) => b.age - b.age); //sort by age in reverse
var maxAge = arr[0].age; //find max age
var output = arr.filter(a => a.age == maxAge).map(a => a.name); //returns array of max age name
console.log(output);

Or find the maxAge first using map

var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
var maxAge = Math.max.apply( null, arr.map( a => a.age ) );
var output  = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name

Demo

var arr = [{name:"john", age:69}, {name:"jane", age:28}, {name:"paul", age: 19}];
var maxAge = Math.max.apply( null, arr.map( a => a.age ) );
var output  = arr.filter( a => a.age == maxAge ).map( a => a.name ); //returns array of max age name
console.log( output );

2 Comments

sort affects the original array. One reduce is sufficient.
@RobG Added another method
0

Since there are answers already… it seems to me reduce is sufficient. Also, I think it's better to always return an array. Functions that return different types depending on some random criterion aren't friendly:

function getOldest(data) {
  var max = -Infinity;
  return data.reduce((acc, obj) => {
    obj.age > max? (acc = [obj.name]) && (max = obj.age) :
    obj.age == max? acc.push(obj.name): null;
    return acc;
  },[]);
}

var data = [{name: 'paul', age: 19}, 
            {name: 'john', age: 69},
            {name: 'jane', age: 28},
            {name: 'fred', age: 13},
            {name: 'tom' , age: 69}];

console.log(getOldest(data));

4 Comments

Why the boolean algebra if you are returning afterwards?
@JonasW.—because it's shorter than if..else and means there's only one return (since the callback needs to return the accumulator). I'm open to a better way.
(acc, obj) => obj.age > max && (max = age) && [obj.name] || obj.age === max && acc.concat(obj) || acc
@JonasW.—that has errors, doesn't return what the OP wants or in the correct format. :-(
0
var myarray = [{name: 'john', age: 35}, {name: 'jane', age: 20}];
var oldest = getoldest(myarray);
alert(oldest.name);

and in the function you could do something like this

function getoldest(myarray){
 var oldest = Math.max.apply(Math,myarray.map(function(myarray){return myarray.age;}));
 var obj = myarray.find(function(o){return o.age == oldest;});
 return obj;
};

This way you could use the returned object for something else.

Comments

0
 function getOldest(arr){

    return arr.reduce( function(acc,current){
       if (acc.age > current.age) {
          return acc
       } else { return current}
    }).name

 }

Edit: It's actually the best method here, just a reduce and that's it, no sorting or filtering.

4 Comments

This just returns the first object with the max age, not what the OP wants. If it was the correct result, consider the simpler: return acc.age > current.age? acc : current, ;-)
No it's not! Next time just check my answer in a compiler.
You could have posted it here as a runnable snippet. It doesn't accommodate duplicates, so not what the OP wants. It will also throw an error if arr is empty as you haven't provided an initial accumulator.
Rob, just be more attentive next time.

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.