0

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')
0

1 Answer 1

2

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);

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

2 Comments

Oh... thanks... using the '[ ]' instead '${ }'... I don't understand why, but for now it's ok. Thanks again
@asaks-, the back-tick with ${} is for string interpolation, so your attempt was appending the object prop name, not accessing the prop. Square braces say, "lookup the prop whose name is the result of the expression inside the brackets"... i.e. first[param] when param is 'name' says get me the name prop from the first object.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.