0

I would like to reorder an array of objects based on one of the nested object's string values. The array has to be in this order. My attempt works but seems like a bloated and possibly inefficient solution:

reorder(order) {
    // create array with 4 null positions
    var newOrder = [null, null, null, null];

    // order can have between 0 - 4 objects
    for(var x = 0; x < order.length; x++){

        // based on value, assign predefined positions
        switch (order[x].slug){
            case 'cheeseburger':
                newOrder[0] = order[x];
                break;
            case 'salad':
                newOrder[1] = order[x];
                break;
            case 'fries':
                newOrder[2] = order[x];
                break;
            case 'iceCream':
                newOrder[3] = order[x];
                break;
        }
    }
    console.log(newOrder);
    return newOrder;
}

How can I reorder the array without creating the null positions?

codepen example

1
  • Please click the <> snippet editor and create a minimal reproducible example - for example what is order ? Commented May 4, 2017 at 7:47

2 Answers 2

2

// assume you have the data arr
var arr = [{
  slug: 'cheeseburger'
}, {
  slug: 'salad'
}, {
  slug: 'fries'
}];

function reorder(arr){
// instead of switch, we put the order into an object
var slugOrder = {
  cheeseburger: 0,
  salad: 1,
  fries: 2
};

// with the native sort function you can get expected results
return arr.sort(function(itemA, itemB) {
  return slugOrder[itemA] - slugOrder[itemB]
});
}
console.log(reorder(arr));

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

1 Comment

Please click the <> and create a real example - for example array.sort ALSO sorts the array in situ so no need to return it: developer.mozilla.org/en/docs/Web/JavaScript/Reference/…
1

You can define a custom comparison function for use with .sort().

Described here: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

Building on Sabrina's answer:

var aMenu = [
 {'name':'A','slug':'salad'},
 {'name':'B','slug':'cheeseburger'},
 {'name':'C','slug':'fries'}];
var oSlugOrder = {'cheeseburger':0,'salad':1,'fries':2};
aMenu.sort(function(oItemA, oItemB){
 return oSlugOrder[oItemA.slug] - oSlugOrder[oItemB.slug]; });

1 Comment

That is a comment. Add the relevant code to make it an answer and your rep will be increased to more than the 50 you need to be allowed to comment

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.