Home > Software design >  Reordering array using .sort with parameters
Reordering array using .sort with parameters

Time:05-30

I have a function to reorder an array with objects inside and I call that function with the object property I want to sort, but I don't know how to set the callback function to use the parameter. I tried use eval() but with no success. It's not working correctly.

function order(param){
  const newOrder = arrayContent.sort((first,second) => (`${first}.${param}` > `${second}.${param}`) ? 1 : -1);
};
order('name')

CodePudding user response:

It's pretty easy to implement. You can refer to object either with 'dot notation' e.g. object.name or with help of square brackets e.g. object['name'] where you could put any string inside brackets to refer to certain 'inner field'

let arrayContent = [{number:3,name:'Alice'},{number:2, name:'Maxim'}]; //your array
    let order = param => arrayContent.sort((first,second) => first[param] < second[param]?1:-1);
    
    order('name');
    console.log(arrayContent);
    order('number');
    console.log(arrayContent);

  • Related