Shariq Ansari
Shariq Ansari

Reputation: 4631

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.

Upvotes: 2

Views: 46

Answers (1)

Nina Scholz
Nina Scholz

Reputation: 386530

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);

Upvotes: 3

Related Questions