Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting nested array based on second value in the inner array in Javascript [duplicate]

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));
like image 427
Madhusudan Avatar asked Mar 10 '23 23:03

Madhusudan


2 Answers

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; }
like image 161
Nina Scholz Avatar answered Mar 13 '23 12:03

Nina Scholz


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);
like image 37
Robby Cornelissen Avatar answered Mar 13 '23 12:03

Robby Cornelissen