0

I'm trying to sort a object array as per colors.

My code:

const colors = [
  {
    "color": "purple",
    "type": true
   
  },
  {
    "color": "red",
    "type": false
  },
{
    "color": "green",
    "type": true
  },
{
    "color": "black",
    "type": false
  },
{
    "color": "pink",
    "type": true
  }]
  

const list = colors.sort((a) => a.color);
console.log(list);
 

How can I achieve this?

halfer
  • 19,824
  • 17
  • 99
  • 186
Rohit Verma
  • 3,657
  • 7
  • 37
  • 75

4 Answers4

3

This code will help you to sort in asc order based on color value.

 const colors = [
      {
        "color": "purple",
        "type": true
       
      },
      {
        "color": "red",
        "type": false
      },
      {
        "color": "green",
        "type": true
      },
      {
        "color": "black",
        "type": false
      },
      {
        "color": "pink",
        "type": true
      }
    ]
    
    const sortedColors = colors.sort((a, b) => {
      if (a.color < b.color) {
        return -1;
      }
      if (a.color > b.color) {
        return 1;
      }
      return 0;
    });
    
    console.log(sortedColors);
NIKUNJ PATEL
  • 2,034
  • 1
  • 7
  • 22
2

Try this, it will work.

You can change condition as per requirement, Thanks.

const colors = [{
    "color": "purple",
    "type": true

  },
  {
    "color": "red",
    "type": false
  },
  {
    "color": "green",
    "type": true
  },
  {
    "color": "black",
    "type": false
  },
  {
    "color": "pink",
    "type": true
  }
]

const result = colors.sort((a, b) => (a.color > b.color) ? 1 : ((b.color > a.color) ? -1 : 0))
console.log(result);
Priyen Mehta
  • 1,096
  • 1
  • 5
  • 19
2

Array.prototype.sort in JavaScript takes in a callback with two parameters.

From MDN,

compareFn(a, b) return value sort order
> 0 sort a after b
< 0 sort a before b
=== 0 keep original order of a and b

However, instead of writing your own comparison function, you can use the builtin String.prototype.localeCompare to compare two strings.

const colors = [
  {
    "color": "purple",
    "type": true
   
  },
  {
    "color": "red",
    "type": false
  },
{
    "color": "green",
    "type": true
  },
{
    "color": "black",
    "type": false
  },
{
    "color": "pink",
    "type": true
  }]
  

const list = colors.sort((a, b) => a.color.localeCompare(b.color));
console.log(list);
Samathingamajig
  • 11,839
  • 3
  • 12
  • 34
-1

Using sort(), you want to compare two elements in the array, so you need to put two parameters in there.

const colors = [
  {
    "color": "purple",
    "type": true
   
  },
  {
    "color": "red",
    "type": false
  },
{
    "color": "green",
    "type": true
  },
{
    "color": "black",
    "type": false
  },
{
    "color": "pink",
    "type": true
  }]
  

const list = colors.sort((a, b) => a.color > b.color);
console.log(list);
cSharp
  • 2,884
  • 1
  • 6
  • 23