Home > Blockchain >  Sort Array in Objects in JSON using JavaScript
Sort Array in Objects in JSON using JavaScript

Time:12-23

I have a unmarshalled string as JSON output called message_obj as shown below. The string was unmarshalled using JSON.pasrse() function. I now need to sort the cars in order of their mileage (from low to high). Can someone please show how will that be possible as I am not sure how arrays inside object works in JavaScript?

{
    username: 'Bob',
    cars: [
      {
        Id: 'car1',
        company: 'bmw',
        mileage: 66
      },
      {
        Id: 'car2',
        company: 'audi',
        mileage: 67
      },
      {
        Id: 'car3',
        company: 'GM',
        mileage: 48
      },
      {
        Id: 'car4',
        company: 'Mercedes',
        mileage: 54
      }
    ]
  }

CodePudding user response:

You can use a sort function to sort based on mileage, by passing it with a function

const x = {
  username: 'Bob',
  cars: [{
      Id: 'car1',
      company: 'bmw',
      mileage: 66
    },
    {
      Id: 'car2',
      company: 'audi',
      mileage: 67
    },
    {
      Id: 'car3',
      company: 'GM',
      mileage: 48
    },
    {
      Id: 'car4',
      company: 'Mercedes',
      mileage: 54
    }
  ]
}

x.cars.sort((a, b) => {
  return a.mileage - b.mileage;
});

console.log(x);

credits - https://www.javascripttutorial.net/array/javascript-sort-an-array-of-objects/

CodePudding user response:

data.cars.sort((a, b) =>
      a.mileage > b.mileage ? 1 : b.mileage > a.mileage ? -1 : 0
    );

Code Sandbox : https://codesandbox.io/s/winter-breeze-qo1cdu?file=/src/App.js:0-694

  • Related