How to sort an attribute based on some attribute of an element EFFECTIVELY

Imagin I have an array

var arr = [{name: 'peter', age: 50}, {name: 'alice', age: 50}, {name: 'zebra', age: 50},];

Now I want to sort them by their name. So, the conclusion is as follows:

[{name: 'alice', age: 50}, {name: 'peter', age: 50}, {name: 'zebra', age: 50}]

The naive solution is to create an array of names and sort them, and then iterate over these sorted names, find the corresponding element in arr and insert into a new array.

I know that this is not the most optimal algorithm, and not the cleanest for writing.

Can anyone do this more efficiently? Also note that I'm using JavaScript, so I'm limited to libraries and built-in javaScript functions, which could be simpler if we use Java or some other similar language, I think.

+4
source share
1 answer

You can use the sortarray function to implement sorting with name, for example:

var arr = [ {name: 'peter', age: 50}, {name: 'alice', age: 50}, {name: 'zebra', age: 50}, ];
arr.sort(function(a,b){ return a.name>b.name; } );

You can read more about this here:

https://developer.mozilla.org/en/docs/Web/JavaScript/Reference/Global_Objects/Array/sort

+5
source

Source: https://habr.com/ru/post/1543590/


All Articles