Home > Blockchain >  JS sort array object by custom key and value
JS sort array object by custom key and value

Time:05-08

I am fresh JS student and I found a problem which I can't sole by my self. I've got an array of objects and one of the key of these objects is 'priority' and values for that key are: "low", "mid", "high". I would like to sort my objects in array from the lowest priority to the highest, but I can't figure it out.

let thingsToDo = [
  {
  name: 'Call',
  priority: 'low',
},
  {
  name: 'Cook',
  priority: 'low',
  },
    {
  name: 'Eat',
  priority: 'high',
  },
                {
  name: 'Sleep',
  priority: 'mid',
  }
];

I was trying to make some custom sort function, but i don't know how to do it. What I think would be a good solution is giving these values some number and then sort it. Very important for me is to leave these values as a string. There has to be priority: "low"

I've been looking for solution sometime and I didn't found it.

I have no idea how to do it, so if there is some good person with a bigger experience, I beg for help.

CodePudding user response:

You can create an object that maps them to comparable values and then sort based on the them:

const priority = {
    low: 1,
    mid: 2,
    high: 3,
};

const sorted = thingsToDo.sort(
    (a, b) => priority[a.priority] - priority[b.priority]
);

Here is a working snippet:

let thingsToDo = [
    {
        name: 'Call',
        priority: 'low',
    },
    {
        name: 'Cook',
        priority: 'low',
    },
    {
        name: 'Eat',
        priority: 'high',
    },
    {
        name: 'Sleep',
        priority: 'mid',
    },
];

const priority = {
    low: 1,
    mid: 2,
    high: 3,
};

const sorted = thingsToDo.sort(
    (a, b) => priority[a.priority] - priority[b.priority]
);

console.log(sorted)

CodePudding user response:

You can place all the priorities in an array and sort the object's based on the index of their priority property in that array.

let thingsToDo = [
  {
  name: 'Call',
  priority: 'low',
},
  {
  name: 'Cook',
  priority: 'low',
  },
    {
  name: 'Eat',
  priority: 'high',
  },
                {
  name: 'Sleep',
  priority: 'mid',
  }
];
let priorities = ['low', 'mid', 'high'];
thingsToDo.sort((a, b)=>priorities.indexOf(a.priority) - priorities.indexOf(b.priority));
console.log(thingsToDo);

CodePudding user response:

try it

const fruits = ["Banana", "Orange", "Apple", "Mango"]; fruits.sort();

  • Related