1

I have an array of objects and I want to sort them by the object ids. I tried using options.sort((a, b) => a.id.localeCompare(b.id)); but did not worked as expected because it is sorting even the 'all' object and I don't want this (the object with id='all' should be first in my array, after that should be the objects in ascending order). Below you can see the input and the output of my code

Input:

 var items = 
           [{ 'Name':'All', 'id': 'all'
            { 'Name':'item1', 'id': '003' }
            { 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }];

Output:

  var items = 
           [{ 'Name':'item2', 'id': '001' }
            { 'Name':'item3', 'id': '002' }
            { 'Name':'item1', 'id': '003' }
            { 'Name':'All', 'id': 'all'}];
1
  • answer modified in a comment again with clean syntax. Commented Apr 22, 2020 at 14:47

2 Answers 2

1

 function compare(key, order = 'desc') {
  return (a, b) => {
    if (a[key] > b[key])
      return order === 'desc' ? -1 : 1;
    if (a[key] < b[key])
      return order === 'desc' ? 1 : -1;
    return 0;
  };
 }


const data = [
      { 'Name':'All', 'id': 'all'},
      { 'Name':'item3', 'id': '003' },
      { 'Name':'item1', 'id': '001' },
      { 'Name':'item2', 'id': '002' }
 ];
 
 const sortedData = data.sort(compare('Name', 'asce'));
 console.log('sorted: ', sortedData);

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

Comments

0

It should work

var items = 
           [{ 'Name':'All', 'id': 'all' },
            { 'Name':'item1', 'id': '003' },
            { 'Name':'item2', 'id': '001' },
            { 'Name':'item3', 'id': '002' }];
            
   items.sort((a, b) => ((typeof b.id === "number") - (typeof a.id === "number")) || (a.id > b.id ? 1 : -1));

// items.sort((a, b) => (((typeof b.id === "number") as any) - ((typeof a.id === "number") as any)) || (a.id > b.id ? 1 : -1) );

  console.log(items)

3 Comments

I get this error 'The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.' for the typeof part..
Updated the answer. Try the commented one for type support
@user2004 The answer is modified again in a comment with a clean syntax.

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.