The sort()
method needs an array as input, but if you call it in the callback function passed to a map()
you are calling it on a single string.
I'm not 100% sure that I understood the desired output, anyway here is my solution.
Let's start with an array of Strings that we want to sort.
const items = ['cat', 'dog', 'elephant', 'bee', 'ant'];
Now in order to sort it without mutating it we can do:
const sortedItems = [...items].sort();
Now we have two arrays, the original one, and another one with the sorted strings.
We can use map()
to loop over the original array and to create the array that you need. The index
parameter in the callback function can be used to retrieve the item in the sorted array.
const newItems = items.map((item, index) => {
return [sortedItems[index], item];
});
Now if I understood correctly we have what you needed:
[
['ant', 'cat'], // 'ant' (from the sorted array), 'cat' (from the original)
['bee', 'dog'], // same thing
['cat', 'elephant'], // etc.
['dog', 'bee'],
['elephant', 'ant']
]
If you want you can put everything together in one function:
const sortingMethod = (items) => {
const sortedItems = [...items].sort();
return items.map((item, index) => {
return [sortedItems[index], item];
});
}
That you can call like this:
const newElements = sortingMethod(['cat', 'dog', 'elephant', 'bee', 'ant']);
console.log(newElements);