Saba Hassan Saba Hassan - 6 months ago 11
Javascript Question

Sort array of array on string value in Javascript

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.

Answer

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"]]