简体   繁体   中英

Reorder elements in array (move to last, move to first, reorder) - JS

I have an array of strings (ids), and a couple of actions I need to do - move to first, move to last, and just swap positions of 2 elements.

I have 2 entry params, initial index of elment, and new index (from what to what position it moved), and array looks like this:

function (initialIndex, newIndex) {
  const arr = ['aaaaa', 'bbbbb', 'ccccc', 'ddddd']
}

This is how I have done reordering, and it works:

[arr[initialIndex], arr[newIndex]] = [arr[newIndex], arr[initialIndex]];

What I need to do now is just to move that single item to last place, or to first place, without swapping those elements. My idea was to have another param to see if it is moved up or down the list, and use that somehow. Any suggestions?

You could use spread operator, put the element you want to place at first/last of the array, and spread the rest element

 const arr = ['aaaaa', 'bbbbb', 'ccccc', 'ddddd', 'eeeee'] function moveToFirst(index, arr) { return [arr[index], ...arr.filter((_, i) => i !== index)] } function moveToLast(index, arr) { return [...arr.filter((_, i) => i !== index), arr[index]] } console.log(moveToFirst(1, arr).join(' ')) console.log(moveToFirst(2, arr).join(' ')) console.log(moveToLast(2, arr).join(' ')) console.log(moveToLast(3, arr).join(' '))

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM