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.
source
share