8

Here's what my array looks like

[
 { name: "myname", date: dateObj, value: 2 },
 { name: "othername", date: dateObj, value: 3 },
 { name: "newname", date: dateObj, value: 5 },
]

Dates are native date objects.

What would be the smartest way to get the one object with the oldest date? Is there a better way than sorting the whole array by looping through?

2
  • 2
    Can you show us what you tried? Commented Sep 23, 2018 at 9:10
  • 1
    Please clarify Is there a better way than sorting the whole array by looping through?. Without iterating through the array, how would you know what's inside it to begin with? It might be that this is the result of some DB query, in which case the best way would be to have the DB sort the returned items. Commented Sep 23, 2018 at 9:20

3 Answers 3

16

You can use Array.reduce() to iterate the array, and on each iteration pick the object with the oldest date:

const data = [
 { name: "myname", date: new Date(2016, 5, 1), value: 2 },
 { name: "othername", date: new Date(2018, 6, 1), value: 3 },
 { name: "newname", date: new Date(2017, 12, 1), value: 5 },
];

const result = data.reduce((r, o) => o.date < r.date ? o : r);

console.log(result);

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

1 Comment

I was wondering about the efficiency of this, so I wrote a little jsperf for it. It's about 50% faster than the sort solutions, for obvious reasons, but it's also significantly faster than a simple for loop, which is a little surprising. jsperf.com/min-value-in-array-rntest
1

Yes. The Array must be pre-sorted. :)

In other words, No. Without iterating the whole Array, there seems no way to find out the Object with oldest date. We need to iterate the Array.

Comments

1

This should do what you want, if we call your array myArray:

myArray.sort((objA, objB) => objA.date.getTime() - objB.date.getTime())[0];

3 Comments

OP was asking for a way to do it without sorting.
Oh OK, perhaps that's what they want. I read it as wanting to do it "without looping through".
The dateA, dateB in .sort() contain object. You should use dateB.date

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.