Manzer A
Manzer A

Reputation: 3806

How to move data in desired format in an array in javascript?

var array = [-3,0,0, 1,55,56,232]

Desired output

array = [56,-3,0,0,1,232,55]

I am facing difficulty in getting desired output. I know this is some easy question but I have tried and not successful. Please help

I have tried like this:--

  array.unshift(array.splice(5, 1)[0]);
  array.unshift(array.splice(4, 1)[0]);

Upvotes: 0

Views: 28

Answers (3)

Dan Porat
Dan Porat

Reputation: 426

how about this (taking advantage of ES6):

array = [array[5], ...array.slice(0,4), array[6], array[4]]

Upvotes: 2

Obsidian Age
Obsidian Age

Reputation: 42304

Perhaps not the most elegant solution, but here's one way of going about it. The unshift() line is the same, in which the sixth element is brought to the start. Next, the last element is grabbed and inserted into the fifth position. Finally, the new last element in the array is removed.

let array = [-3, 0, 0, 1, 55, 56, 232]

array.unshift(array.splice(5, 1)[0]);
array.splice(array[array.length - 1], 0, array[array.length - 1]);
array.pop();

console.log(array);

Upvotes: 1

Kirill Simonov
Kirill Simonov

Reputation: 8481

You shuold use push instead of unshift second time as you want to move 55 to the end of the array. Also after you do splice and unshift the first time, the index of 55 becomes 5, because you move 56 to the begining.

let array = [-3, 0, 0, 1, 55, 56, 232];
array.unshift(array.splice(5, 1)[0]);
array.push(array.splice(5, 1)[0]);
console.log(array);

Upvotes: 1

Related Questions