0

I have an array like this

 let years =[
       {id: 3, name: "2016", age: "None"},
       {id: 1, name: "2017", age: "None"},
       {id: 2, name: "2015", age: "None"},
       {id: 5, name: "2018", age: "None"},
       {id: 3, name: "2018/2019", age: "None"}
       ]
       
years.sort((c1, c2) => {
        return c2.name - c1.name;
       });
       
console.log(years);       

I couldn't deal with this "2018/2017" way how can I do it what is the best way to do it

4 Answers 4

3

You can use localeCompare

const years = [
    { id: 3, name: '2016', age: 'None' },
    { id: 1, name: '2017', age: 'None' },
    { id: 2, name: '2015', age: 'None' },
    { id: 5, name: '2018', age: 'None' },
    { id: 3, name: '2018/2019', age: 'None' },
];

years.sort((c1, c2) => c2.name.localeCompare(c1.name));

console.log(years);

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

Comments

1

You are almost there...Just a little change in your sort callback and it's done::

let years = [
    { id: 3, name: '2016', age: 'None' },
    { id: 1, name: '2017', age: 'None' },
    { id: 2, name: '2015', age: 'None' },
    { id: 5, name: '2018', age: 'None' },
    { id: 3, name: '2018/2019', age: 'None' },
];
years.sort((c1, c2) => {
    var n1 = c1.name;
    var n2 = c2.name;
    if(n1 > n2){return -1;
    }else if(n2 > n1){ return 1;
}else{return 0;}
   });
console.log(years);

Comments

0

Try this:

years.sort((c1, c2) => {
  if (c1.name > c2.name) return -1;
  if (c1.name < c2.name) return 1;
  return 0;
});

Comments

0

You could use lodash _.sortBy

var years =
[{id: 5, name: "2018", age: "None"},
 {id: 3, name: "2018/2017", age: "None"},
 {id: 1, name: "2017", age: "None"},
 {id: 3, name: "2016", age: "None"},
 {id: 2, name: "2015", age: "None"}]

_.sortBy(years, ['name']);

Output would be

enter image description here

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.