0

I'm mapping thought an array and i'm getting inside this array multiple object that look like this

{time: 14, pokemon: true},
{time: 12, pokemon: true}

Here is my map:

cont mapObject = arr.map(x => x)

Is it anyway to sort the objects by ascending time ?? I'm not really sure how to place a sort function

Yannis
  • 21
  • 1
  • 6
  • [The array has a `.sort()` method, and you can pass it a callback to indicate the desired ordering.](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort) – Pointy Nov 12 '19 at 13:49

2 Answers2

0

The .sort property of arrays takes in a sorting argument, use like this:

let sortedArr = someArr.sort((a,b) => a.time - b.time);
Strike Eagle
  • 852
  • 5
  • 19
0

It is easy to sort the data. Since it is already an array, just sort by the time by subtracting A from B.

Sorting is not in-place, so you have to assign the sorted data back to itself to another variable.

var data = [
  { time: 14, pokemon: true },
  { time: 12, pokemon: true }
];

data = data.sort((a, b) => a['time'] - b['time']);

console.log(data);
.as-console-wrapper { top: 0; max-height: 100% !important; }
Mr. Polywhirl
  • 42,981
  • 12
  • 84
  • 132