Move an Array Element from One Array Position to Another

Move an array element from one array position to another

If you'd like a version on npm, array-move is the closest to this answer, although it's not the same implementation. See its usage section for more details. The previous version of this answer (that modified Array.prototype.move) can be found on npm at array.prototype.move.


I had fairly good success with this function:

function array_move(arr, old_index, new_index) {

if (new_index >= arr.length) {

var k = new_index - arr.length + 1;

while (k--) {

arr.push(undefined);

}

}

arr.splice(new_index, 0, arr.splice(old_index, 1)[0]);

return arr; // for testing

};

// returns [2, 1, 3]

console.log(array_move([1, 2, 3], 0, 1));

Move an element to the front of an array: Javascript

You can make use of Array.unshift and Array.splice.

let arr = [{name:"test1",id:5},{name:"test2",id:6},{name:"test3",id:8}]

const moveToFront = (data, matchingId) => {
//find the index of the element in the array
const index = data.findIndex(({id}) => id === matchingId);
if(index !== -1) {
//if the matching element is found,
const updatedData = [...data];
//then remove that element and use `unshift`
updatedData.unshift(...updatedData.splice(index, 1));
return updatedData;
}
//if the matching element is not found, then return the same array
return data;
}

console.log(moveToFront(arr, 6));
.as-console-wrapper {
max-height: 100% !important;
}

Change elements positions in an array and shift elements in between

You can use Array.prototype.splice to cut out the element you want and insert at the desired index (the shifting will happen automatically):

function insertAndShift(arr, from, to) {

let cutOut = arr.splice(from, 1) [0]; // cut the element at index 'from'

arr.splice(to, 0, cutOut); // insert it at index 'to'

}

let data = [ 0, 1, 2, 3, 4, 5, 6 ];

insertAndShift(data, 0, 3);

console.log("[" + data + "]");

insertAndShift(data, 3, 0);

console.log("[" + data + "]");

Shift the position of an element in an array

You need to cover the edge cases when the updated index is less than 0 OR greater than the array length. You can try following

const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9];

function move(array, index, offset) {

const output = [...array];

const element = output.splice(index, 1)[0];

let updatedIndex = index + offset;

if(updatedIndex < 0) updatedIndex++;

else if (updatedIndex >= array.length) updatedIndex -= array.length;

output.splice(updatedIndex, 0, element);

return output;

}

console.log(move(numbers, 3, -5));

How to change position of items within an array?

If I understood properly, I think you can simplify in one line function:

const moveLeft = (arr) => arr.push(a.shift());

Notice that this function would mutate the content of the array but I guess that what you want:

const array = [1, 2, 3];

moveLeft(array);
console.log(array)// [2, 3, 1]

moveLeft(array);
console.log(array)// [3, 1, 2]

moveLeft(array);
console.log(array)// [1, 2, 3]

Basically with push we add a new element at the end of the array, and the new element we add, is the return value of the method shift, that removes the first element from an array and return it.

Edit

If you don't want to mutate the original array, the fastest way is create a shallow copy and pass that to the function:

 const newArray = array.slice();
moveLeft(newArray);

console.log(newArray, array) // [2, 1, 3] [1, 2, 3]

However, a possible implementation that always return a new array, could be:

 const moveLeft = (arr) => [...arr.slice(1), arr[0]]

Just for future reference. But keep in mind that here you're create a shallow copy, (so one new array) and returns a new array from the spread operator, so it's less ideal. It could be useful only if you're writing an API that never allow mutability.

Edit 2

As per comment, the input's value should reflect the new order, so, given the moveLeft function written before (the first one, that mutates the content):

<input id="numero1" value="">
<button onclick="inputMoveLeft('numero1')">Move</button>

And the JS:

function inputMoveLeft(id) {
const input = document.getElementById(id);

input.value = moveLeft(input.value.split("")).join("");
}

It should give you the result you were looking for.

Move an array element from a position to another with condition

Try with Array#sort() compare the value matching with EUR .its matching set with first place with in a array

var array = [{ label: 'yu', value: 'uy'},  { label: 'EUR', value: 'EUR'  },{ label: 'CY', value: 'CY' }]

console.log(array.sort((a, b) => a.value == 'EUR' ? -1 : b.value == 'EUR' ? 1 : 0))

Move array objects/elements Up and Down by index

If you want to perform the same thing with your array, all you need to do is to check if the given element has a previous or a next element so you can swap both objects to avoid an index out of bound.

This is how should be your code:

function moveUp(id) {
let index = arr.findIndex(e => e.id == id);
if (index > 0) {
let el = arr[index];
arr[index] = arr[index - 1];
arr[index - 1] = el;
}
}

To move an element up in the array, you need to make sure this element isn't the first element in the array, then perform the swap operation.

function moveDown(id) {
let index = arr.findIndex(e => e.id == id);
if (index !== -1 && index < arr.length - 1) {
let el = arr[index];
arr[index] = arr[index + 1];
arr[index + 1] = el;
}
}

To move an element down, you need to make sure this element isn't the last one in the array.

Demo:

This is a working Demo sample:

var arr = [

{ id: "Racer-101", rank: "1"},

{ id: "Racer-102", rank: "2"},

{ id: "Racer-103", rank: "3"},

{ id: "Racer-104", rank: "4"},

{ id: "Racer-105", rank: "5"},

{ id: "Racer-106", rank: "6"},

{ id: "Racer-107", rank: "7"},

{ id: "Racer-108", rank: "8"},

{ id: "Racer-109", rank: "9"}

];

function moveUp(id) {

let index = arr.findIndex(e => e.id == id);

if (index > 0) {

let el = arr[index];

arr[index] = arr[index - 1];

arr[index - 1] = el;

}

}

function moveDown(id) {

let index = arr.findIndex(e => e.id == id);

if (index !== -1 && index < arr.length - 1) {

let el = arr[index];

arr[index] = arr[index + 1];

arr[index + 1] = el;

}

}

moveDown("Racer-101");

moveUp("Racer-103");

console.log(arr);

Move multiple array elements from one array position to another

Make a new array with the output you expect. Also, I would suggest to use indexOf instead of includes as includes will give you error in IE browser. You can also make use of spread syntax ... that will add the array elements to your new array.

const countryList1 = ['Afghanistan','Albania', 'Argentina', 'Australia', 'Bangladesh', 'Belgium','Brazil'];

const countriesInFirst = ['Argentina', 'Australia','Belgium', 'Brazil'];

const countryList2 = [

...countriesInFirst,

...countryList1.filter(country => countriesInFirst.indexOf(country) === -1)

];

console.log(countryList2);


Related Topics



Leave a reply



Submit