1

Say I have this array

arr = ["me", "you", "us", "them"]

I want to be able to move each array element up an index when I click on it, e.g when I click on "them" the array should be like

arr = ["me", "you", "them", "us" ]

I want to use splice() in theory it seems simple but I just can't get my head around it. This is my code

    moveRowUp = (to, frm) => {
    const {layout} = this.state
    if(to >= layout.length){
        let diff = to - layout.length;
        while((diff--) + 1){
            layout.push(undefined)
        }
    }
    layout.splice(to, 0, layout.splice(to, 1)[0]);
    // this.setState({
    //     layout: layout
    // })
}
4
  • 1
    How to create a Minimal, Complete, and Verifiable example Commented May 29, 2017 at 11:42
  • 1
    Why don't you also post the code that you tried to achieve this? Commented May 29, 2017 at 11:43
  • @HimanshuTyagi I just edited and updated with my code Commented May 29, 2017 at 11:46
  • you just need a simple swap to achieve this. swap(item, item-1) Commented May 29, 2017 at 11:51

3 Answers 3

3

Instead of using splice, why don't you just swap two values?

function moveUp(arr, index) {
  if (index > 0) {
    _swap(arr, index, index - 1);
  }
}

function moveDown(arr, index) {
  if (index < arr.length - 1) {
    _swap(arr, index, index + 1);
  }
}

function _swap(obj, prop1, prop2) {
  var tmp = obj[prop1];
  obj[prop1] = obj[prop2];
  obj[prop2] = tmp;
}
Sign up to request clarification or add additional context in comments.

Comments

1

That would be my approach using splice.

const words = ['first', 'second', 'third'];

function click(i) {
  if (i < words.length)
    words.splice(i+1, 0, words.splice(i, 1).pop());
}

click(1);
console.log(words);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comments

0

Example:

const a = ["me", "you", "us", "them"];

const moveLeft = arr => word => {
  const i = arr.indexOf(word);
  if (i > -1) {
    arr.splice(i, 1); 
    arr.splice((i !== 0) ? i-1 : arr.length, 0, word) // handle 0 index
  }
  return a;
}

console.log(moveLeft(a)('them'))

Comments

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.