1

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]

1
  • 1
    use array.splice - or a simple swap Commented Nov 28, 2019 at 2:31

4 Answers 4

3

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

Sign up to request clarification or add additional context in comments.

Comments

0

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)

Comments

0

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)

1 Comment

your moveTo doesn't work if from is smaller than to. moveTo(d, 4, 1) gives ["a", "b", "c", "d", "e", "f"]
0

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

4 Comments

OP doesn't want to swap two values, they just want to move b to the location of e
Yeah the OP doesn't wan to swap the values.
This doesn't produce the answer they wants. This will produce [a, e, c, d, b, f], they want [a, c, d, e, b, f]
Fixed now, though slightly redundant given that other answers have been posted - Thanks for drawing my attention to the mistake

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.