0

I have an array of objects like this

layerArr = [
            {
               name: "layer 1"
               layerDate: "/Date(6958748400000)/"
               layerDateFormatted: "31 December 2018"
               etc...
            }
            {
               name: "layer 2"
               layerDate: "/Date(9375937500000)/"
               layerDateFormatted: "23 December 2017"
               etc...
            }
            {
               name: "layer 3"
               layerDate: "/Date(1554764400000)/"
               layerDateFormatted: "15 January 2018"
               etc...
            }]

How can I sort layerArr by date with the latest date first? In this example, when layer 2 is sorted correctly, I also want the latest date to become layer 1 and the oldest date should become the last layer. (the example above is made up values)

Thanks

EDIT: the links suggested to other threads do not explain how to change "name" so that the latest date becomes name ="layer 1" all the way to the oldest date becoming the last layer.

5

1 Answer 1

4

Use Array.sort():

layerArr = [
  { name: "layer 1", layerDate: "/Date(6958748400000)/", layerDateFormatted: "31 December 2018" },
  { name: "layer 2", layerDate: "/Date(9375937500000)/", layerDateFormatted: "23 December 2017" },
  { name: "layer 3", layerDate: "/Date(1554764400000)/", layerDateFormatted: "15 January 2018" }
];
            
sortedLayerArr = layerArr.sort(function(a, b) {
  return new Date(a.layerDateFormatted)- new Date(b.layerDateFormatted);
}).map((layer, index) => ({
  ...layer,
  name: `layer ${index + 1}`,
}));

console.log(layerArr);
console.log(sortedLayerArr);

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

4 Comments

Thanks, this sorts by date, but it does not change the "name" property accordingly so that the latest date becomes "layer 1" all the way to the oldest date which should become the last layer.
@NickyLarson this was not mentioned before in the question
It was, the only edit I have made is the part with EDIT
@NickyLarson that is not a big problem you can just loop over the sorted array and update the name in loop

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.