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));