Bas Tichelaar
Bas Tichelaar

Reputation: 407

Javascript/JSON: Swap items in array

I'm pretty new to Javascript, and want to swap the items of an array in an array. Example:

{
    "data": [
        [null, 1353064450],
        [null, 1353064460],
        [null, 1353064470],
        [null, 1353064480],
        [null, 1353064490]
        ],
    "label": "cpu"
}

should become:

{
    "data": [
        [1353064450, null],
        [1353064460, null],
        [1353064470, null],
        [1353064480, null],
        [1353064490, null]
        ],
    "label": "cpu"
}

I probably have to iterate through the array and create a new array? Any pointers would be great!

Upvotes: 1

Views: 973

Answers (2)

user1726343
user1726343

Reputation:

With modern JS, you can just do obj.data = obj.data.map(([x, y]) => [y, x]).

Support across browsers might be patchy, so you should use a transpiler that turns this into ES5, at least for the near future.

Original answer:

Use the Array.reverse method:

var obj = {
    "data": [
        [null, 1353064450],
        [null, 1353064460],
        [null, 1353064470],
        [null, 1353064480],
        [null, 1353064490]
        ],
    "label": "cpu"
};
for(var i=0; i< obj.data.length; i++){
     obj.data[i].reverse();
}

Upvotes: 3

I Hate Lazy
I Hate Lazy

Reputation: 48789

Here's a fun way that will work in modern browsers (e.g. IE9 and higher):

response.data.forEach(Function.call.bind([].reverse));

Or if you do this a lot where you need a .call method with its this value bound to a method that itself operates on a this value (as above), you can make a reusable .call binder.

var callBind = Function.bind.bind(Function.call);

  // Then use it like this
response.data.forEach(callBind([].reverse));

Upvotes: 0

Related Questions