-1

I want to sort the array of array on length of string, as follows

var arr = [
   [1951, "Mayfer"],
   [1785, "Actinac Capsules"],
   [1007, "Ferri Injection"],
   [1101, "Cetaphil"]
];

var sortedArr = sortOnLengthOfString(arr);

>> sortedArr = [
  [1951, "Mayfer"],
  [1101, "Cetaphil"],
  [1007, "Ferri Injection"],
  [1785, "Actinac Capsules"]
]

Is there a solution with lodash preferably? Or plain Javascript?

I haven't found duplicate question yet. Can someone find it? Please note, the sorting I am asking for, is for array of arrays and not array of objects.

Saba
  • 3,418
  • 2
  • 21
  • 34

1 Answers1

2

You can use Array#sort at this context,

var obj = [
   [1951, "Mayfer"],
   [1785, "Actinac Capsules"],
   [1007, "Ferri Injection"],
   [1101, "Cetaphil"]
];

obj.sort(function(a,b){ 
    return a[1].length - b[1].length 
});

console.log(obj);
//[[1951, "Mayfer"],[1101, "Cetaphil"],[1007, "Ferri Injection"],[1785, "Actinac Capsules"]]
Rajaprabhu Aravindasamy
  • 66,513
  • 17
  • 101
  • 130