How to Change the Position of an Array Element

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

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.

How to change the position of an array element?

Nothing is simpler:

array.insert(2, array.delete_at(7))

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 + "]");

How to replace item in array?

var index = items.indexOf(3452);

if (index !== -1) {
items[index] = 1010;
}

Also it is recommend you not use the constructor method to initialize your arrays. Instead, use the literal syntax:

var items = [523, 3452, 334, 31, 5346];

You can also use the ~ operator if you are into terse JavaScript and want to shorten the -1 comparison:

var index = items.indexOf(3452);

if (~index) {
items[index] = 1010;
}

Sometimes I even like to write a contains function to abstract this check and make it easier to understand what's going on. What's awesome is this works on arrays and strings both:

var contains = function (haystack, needle) {
return !!~haystack.indexOf(needle);
};

// can be used like so now:
if (contains(items, 3452)) {
// do something else...
}

Starting with ES6/ES2015 for strings, and proposed for ES2016 for arrays, you can more easily determine if a source contains another value:

if (haystack.includes(needle)) {
// do your thing
}

How to change array element position without swapping in Vuejs?

I guess the code is fine but, it needs tweaks:

  1. You must remove the 6th position via arr.splice(index, 1)
  2. Then insert the 1st postion via arr.splice(index, 0, tmp)

Please see JS Splice

groupsCall(callType, params) {
let url = `/api/v3/campaigns/${this.campaignId}/`,
errorMessage = `could not load the filters`;

url =
callType === "get" ? url + "selected_groups" : url + "update_groups";

axiosConfig[callType](url, params)
.then((response) => {
const data = response.data;
console.log("hittttt", data.groups_with_selected);

let tmp = data.groups_with_selected[6];
// Remove the 6th position
data.groups_with_selected.splice(6, 1)
// Insert tmp
data.groups_with_selected.splice(1, 0, tmp)
// This code is not needed
// data.groups_with_selected[6] = tmp;
if (isObject(data)) {
this.setGroupsData(data);
this.getTotalCount();
errorMessage = "";
this.setUpdating(data);
}
this.errorMessage = errorMessage;
})
.catch((error) => {
errorMessage = `${errorMessage}. ${error}`;
this.errorMessage = errorMessage;
this.updating = false;
});
},

How to change position of an element in an array?

If you can do an increment of one, just repeat that the required number of times.

A better way would be: (let's call the increment n); store the end n elements in another array; move the elements before that towards the end of the array; copy back the elements from the other array to the start. Like this:

Module Module1

Sub Main()
Dim players() As String = {"Adam", "Becky", "Clive", "Debby", "Edward", "Fiona"}
Dim rotateBy = 2

' make sure shiftBy is in a usable range
rotateBy = rotateBy Mod players.Length
' if shiftBy is negative, make it positive such that a left-rotate is performed
If rotateBy < 0 Then
rotateBy = rotateBy + players.Length
End If

' store the elements which will be moved to the other end of the array
Dim tmp(rotateBy - 1) As String
Dim startIndex = players.Length - rotateBy
For i = startIndex To players.Length - 1
tmp(i - startIndex) = players(i)
Next

' move the elements
For i = players.Length - 1 - rotateBy To 0 Step -1
players(i + rotateBy) = players(i)
Next

'fill in the other elements
For i = 0 To rotateBy - 1
players(i) = tmp(i)
Next

' show the result
Console.WriteLine(String.Join(", ", players))

Console.ReadLine()

End Sub

End Module

Note that the copying of elements within the players array is done backwards so that an overlapping range does not splat over values which have yet to be moved.

To shift the elements backwards, use a negative value for rotateBy.

If you are using a language with a function which gives array copying functions, this method is easy to adapt to use that functionality. For anyone wondering about that in the future:

Module Module1

Sub Main()
Dim players() As String = {"Adam", "Becky", "Clive", "Debby", "Edward", "Fiona"}
Dim rotateBy = 4

' make sure shiftBy is in a usable range
rotateBy = rotateBy Mod players.Length
' if shiftBy is negative, make it positive such that a left-rotate is performed
If rotateBy < 0 Then
rotateBy = rotateBy + players.Length
End If

' store the elements which will be moved to the other end of the array
Dim tmp(rotateBy - 1) As String
Dim startIndex = players.Length - rotateBy

Array.Copy(players, startIndex, tmp, 0, rotateBy)
Array.Copy(players, 0, players, rotateBy, startIndex)
Array.Copy(tmp, players, tmp.Length)

' show the result
Console.WriteLine(String.Join(", ", players))

Console.ReadLine()

End Sub

End Module

As you mentioned any programming language, this is what it could be in C# as a function but without using any framework methods such as Array.Copy:

public static void RotateUsingLoops<T>(T[] elements, int rotateBy)
{
rotateBy = rotateBy % elements.Length;
if (rotateBy < 0)
{
rotateBy += elements.Length;
}
T[] tmp = new T[rotateBy];
int startIndex = elements.Length - rotateBy;

// store the elements which will be moved to the other end of the array
for (int i = startIndex; i < elements.Length; i++)
{
tmp[i - startIndex] = elements[i];
}

// move the elements
for (int i = elements.Length - 1 - rotateBy; i >= 0; i--)
{
elements[i + rotateBy] = elements[i];
}

// fill in the other elements
for (int i = 0; i < rotateBy; i++)
{
elements[i] = tmp[i];
}
}

Whereby you could use

static void Main(string[] args)
{
var a = new string[] { "A", "B", "C", "D" };
RotateUsingLoops(a, 2);
Console.WriteLine(string.Join(", ", a));

Console.ReadLine();

}

to get an output of:

C, D, A, B

Change position of array element

If you don't want to change the original array, you can find the index (Array.findIndex()), and then construct a new array by putting the element at the index at the top, and spreading the slices that come before and after the index:

const moveToTop = (name, arr) => {

const idx = arr.findIndex(o => o.name === name);



if(idx === -1) return arr;



return [

arr[idx],

...arr.slice(0, idx),

...arr.slice(idx + 1)

]

}

const cards = [{"name":"a","value":"234"},{"name":"b","value":"876"},{"name":"c","value":"765"},{"name":"d","value":"980"}];

const defaultCard = 'c';

const result = moveToTop(defaultCard, cards);

console.log(result);


Related Topics



Leave a reply



Submit