Skip to content

Array.prototype.sort(): "Sorting with map": looks like example is pointless, or I do not understand it #3115

@vitaly-zdanevich

Description

@vitaly-zdanevich

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

var list = ['Delta', 'alpha', 'CHARLIE', 'bravo'];
// temporary array holds objects with position and sort-value
var mapped = list.map(function(el, i) {
return { index: i, value: el.toLowerCase() };
})
// sorting the mapped array containing the reduced values
mapped.sort(function(a, b) {
if (a.value > b.value) {
return 1;
}
if (a.value < b.value) {
return -1;
}
return 0;
});
// container for the resulting order
var result = mapped.map(function(el){
return list[el.index];
});

By the library link from the article I found better explanation of this idea. I mean we should add more accent about performance, by adding a call to some expensive function.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions