I am working on a script in which I have to sort arr of arrays based on second element of inner arrays. For example here below I mentioned array:
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
I want to sort this array based on all string values in inner arrays. So result should be:
var result = [
[67, "Bowling Ball"],
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[7, "Toothpaste"]
];
For this I have written following script: Is there any other way to do same thing? May be without creating object?
function arraySort(arr) {
var jsonObj = {};
var values = [];
var result = [];
for (var i = 0; i < arr.length; i++) {
jsonObj[arr[i][1]] = arr[i][0];
}
values = Object.keys(jsonObj).sort();
for (var j = 0; j < values.length; j++) {
result.push([jsonObj[values[j]], values[j]]);
}
return result;
}
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
console.log(arraySort(newInv));
You could use Array#sort
The
sort()
method sorts the elements of an array in place and returns the array. The sort is not necessarily stable. The default sort order is according to string Unicode code points.
with String#localeCompare
The
localeCompare()
method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order.
var newInv = [[2, "Hair Pin"], [3, "Half-Eaten Apple"], [67, "Bowling Ball"], [7, "Toothpaste"]];
newInv.sort(function (a, b) {
return a[1].localeCompare(b[1]);
});
console.log(newInv);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Sure, like this, using Array
's sort()
method:
newInv.sort((a, b) => a[1].localeCompare(b[1]));
Here's a snippet:
var newInv = [
[2, "Hair Pin"],
[3, "Half-Eaten Apple"],
[67, "Bowling Ball"],
[7, "Toothpaste"]
];
newInv.sort((a, b) => a[1].localeCompare(b[1]));
console.log(newInv);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With