EN
JavaScript - sort array based on length of each element
0 points
In this article, we would like to show you how to sort array based length of each element in JavaScript.
Quick solution (ES6):
xxxxxxxxxx
1
const array = ['12', '123', '1'];
2
3
array.sort((a, b) => a.length - b.length);
4
5
console.log(array); // [ '1', '12', '123' ]
In this example, we sort the elements in the array from the shortest to the longest ones.
xxxxxxxxxx
1
var array = ['12', '1', '123', '1234'];
2
3
array.sort(function(a, b) {
4
return a.length - b.length;
5
});
6
7
console.log(array); // [ '1', '12', '123', '1234' ]
In this example, we sort the elements in the array from the longest to the shortest ones.
xxxxxxxxxx
1
var array = ['12', '1', '123', '1234'];
2
3
array.sort(function(a, b) {
4
return b.length - a.length;
5
});
6
7
console.log(array); // [ '1234', '123', '12', '1' ]