Shariq Ansari Shariq Ansari - 1 month ago 11
Javascript Question

Change index of array values with keys

After running a function i am getting an array like this.

["1:s", "2:2", "0:f"]


but i want to convert this array like this

["0:f","1:s","2:2"]


i mean index should be same as key.

Answer

You could just sort it with taking the index out of the string.

var array = ["1:s", "2:2", "0:f"];
array.sort(function (a, b) {
    return a.split(':')[0] - b.split(':')[0];
});
console.log(array);