sera
sera

Reputation: 83

Changing array position in javascript

I want to move to the part I want in the array [a, b, c, d, e, f]. For example, how do you move b with index 1 to e? The array I want is: [a, c, d, e, b, f]

Upvotes: 1

Views: 143

Answers (4)

Shiny
Shiny

Reputation: 5055

Using Array.splice:

This gives us an array containing just the element from the index you give:

arr.splice(from, 1)

We then insert this at the chosen index (Using the spread operator to expand the array)

arr.splice(to, 0, ...arr.splice(from, 1))

let arr = ['a', 'b', 'c', 'd', 'e', 'f'];

function moveElement (targetArray, from, to) {
  targetArray.splice(to, 0, ...targetArray.splice(from, 1))
}

moveElement(arr, 1, 4);

console.log(arr);

Upvotes: 0

Kalimah
Kalimah

Reputation: 11437

You can use .splice()

.splice first argument is the start position where you want to delete. The second argument is how many elements you want to delete. Then the rest of arguments are elements you want to append at the deleted element index.

const array = ['a', 'b', 'c', 'd', 'e', 'f'];

// Delete element and save it to a variable
const el = array.splice(1, 1);

// Add deleted element to the required position
array.splice(4, 0, el[0]);


console.log(array);

Upvotes: 3

David Japan
David Japan

Reputation: 242

You can use temp variable for temporary store data and loop from your wanted move index to target index

var d = ['a', 'b', 'c', 'd', 'e', 'f'];
function moveTo(data, from, to) {
  let _tmp = data
  let _move = data[from]
  for(var i = from; i <= to; i++) {
     if(i === to) _tmp[i] = _move
     else _tmp[i] = data[i+1]
  }
  data = _tmp
}

moveTo(d, 1, 4)
console.log(d)

Upvotes: 0

Prasanna
Prasanna

Reputation: 4636

I think you can object destructure to create what you are looking for. Though, I am not sure if this is the best way you can do it.

const a = ['a', 'b', 'c', 'd', 'e', 'f']


// I would just create a new array that would work like this

const newA = [
   // everything before index 1
   ...a.slice(0, 1),
   
   // everything after index 1 till index 4 and then the index 1
   ...[...a.slice(1+1,4+1), a[1]],
   
   // everything after index 4
   ...a.slice(4+1)
]

console.log(newA)

Upvotes: 0

Related Questions