4

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));
Madhusudan
  • 4,637
  • 12
  • 55
  • 86
  • *"without creating json object"* - You haven't created a "JSON object" ([there's no such thing](http://benalman.com/news/2010/03/theres-no-such-thing-as-a-json/)), you've created an "object". – nnnnnn Oct 10 '16 at 06:45

3 Answers3

5

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; }
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
3

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);
Robby Cornelissen
  • 91,784
  • 22
  • 134
  • 156
0

Duplicate of sort outer array based on values in inner array, javascript here you will find several answers, like my own

var arr = [.....]
arr.sort((function(index){
    return function(a, b){
        return (a[index] === b[index] ? 0 : (a[index] < b[index] ? -1 : 1));
    };
})(2)); // 2 is the index

This sorts on index 2

Community
  • 1
  • 1
Ali Hesari
  • 1,821
  • 5
  • 25
  • 51