AngularJS or Javascript: Sort array(ASC & DESC) using index only

Assume i have a javascript object, like so:

var arrObject = [
{id:'01', name:'John'},
{id:'02', name:'Joseph'},
{id:'03', name:'Tom'},
{id:'04', name:'Nick'}
];

I have to sort the object in DESC order by index only. To sort, should not use any key from the object.
Result:

var arrObject = [
{id:'04', name:'Nick'},
{id:'03', name:'Tom'},
{id:'02', name:'Joseph'},// to be remove
{id:'01', name:'John'},
];

Suppose I have deleted third item i.e. id = ’02’, and added new item object. Now, Object looks:

var arrObject = [
{id:'05', name:'Harrison'}, //new added item
{id:'04', name:'Nick'},
{id:'03', name:'Tom'},
{id:'01', name:'John'}
];

So, whenever I perform Add/Delete operation on the object I have to sort the array in DESC order by index only. That way I can keep the new item on top always and so on.

Note: No need to put the additional key in the object for sort purpose, as items from the object can be removed or added.

I do not see any built-in method would work for this directly, if yes that would great. If not, how would you go about writing a method that does this? Any help would be appreciated !!

Solution preferred in AngularJS, but Javascript also welcomed.

Here is Solutions:

We have many solutions to this problem, But we recommend you to use the first solution because it is tested & true solution that will 100% work for you.

Solution 1

First – arrObject is an array of objects – this allows an index in the first place.

This issue seems to be a js only issue – simply use unshift() to add new items to the start of the array

var arrObject = [
{id:'05', name:'Harrison'},
{id:'04', name:'Nick'},
{id:'03', name:'Tom'},
{id:'01', name:'John'}
];

arrObject.unshift({id:'06', name:'Gavin'});

console.log(arrObject); // puts the newly added Gavin object ar ethe start of the array.

but if you really want to push an item to the end of the array then – .reverse() would seem to be what you want – ie array.reverse() will present the array from the end to the start

var arrObject = [
{id:'01', name:'John'},
{id:'03', name:'Tom'},
{id:'04', name:'Nick'},
{id:'05', name:'Harrison'},
];

arrObject.push({id:'06', name:'Gavin'});// puts the Gavin object ar ethe end of the array.

console.log(arrObject.reverse()); // renders the array in reverse orderwith the Gavin object shown first

Note: Use and implement solution 1 because this method fully tested our system.
Thank you 🙂

All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply