I was working on a project when I faced an unprecedented and obvious issue. How do I suppose to move an element in an array form one position to another?
My goal is to move an element in index-0 to index-2. Something like this:
const input = ["a", "b", "c"];
const expected = ["b", "c", "a"];
The simplest way, using splice()
which gives me the ability to add and remove elements in an array.
First, let's delete element in index-0:
function move(input, from) {
const numberOfDeletedElm = 1;
// delete one element only, in index-from
const arrDeletedElem = input.splice(from, numberOfDeletedElm);
// ["a"]=["a", "b", "c"].splice(0, 1);
// and input array is ["b", "c"]
}
But, I don't need an array, I only need the content of the arrDeletedElem
.
const elm = input.splice(from, numberOfDeletedElm)[0];
Now, let's add elm
to index-2
const numberOfDeletedElm = 0;
input.splice(2, numberOfDeletedElm, elm);
And our move
function well be:
function move(input, from, to) {
let numberOfDeletedElm = 1;
const elm = input.splice(from, numberOfDeletedElm)[0];
numberOfDeletedElm = 0;
input.splice(to, numberOfDeletedElm, elm);
}
// move(["a", "b", "c"], 0, 2) >> ["b", "c", "a"]
Of course, this can go deeper, that's why I created move-position. Which contains utility functions for moving index in an array.
Since releasing V1, move-position can deal with the following cases:
1- Moving one element form/to index using: move
.
const input = ["a", "b", "c"];
// move element form index=0, to index=2
const result = move(input, 0, 2);
// ["b", "c", "a"];
2- Moves the same form/to index in multiple arrays using: moveMultiArr
.
const input1 = ["a1", "b1", "c1"];
const input2 = ["a2", "b2", "c2"];
const inputs = [input1, input2];
const result = moveMultiArr(inputs, 2, 0);
// result[0] > ["c1", "a1", "b1"];
// result[1] > ["c2", "a2", "b2"];
3- Moves multiple indexes in the same array using: moveMultiIndex
.
const input = ["a", "b", "c"];
const movingMap = [
{ from: 0, to: 2 },
{ from: 2, to: 1 }
];
const result = moveMultiIndex(input, movingMap);
// result > [ 'a', 'c', 'a' ]
And it's well-tested:
Do you like it? Please leave a ⭐️. I appreciate any feedback or PRs 👋👋👋
Top comments (4)
Your move function doesnt return anything.
Which means its mutating the array directly or your code doesnt work.
Either way you will need to fix it.
It works perfectly with tests
github.com/jalal246/move-position/...
I think they just meant that you shouldn't mutate the original array/object directly. Best practice would be to return a new array with the correctly arranged elements within it.
Would be a minor code change, and would be more widely accepted since you should never mutate original data in a black box style function call.
It's optional just pass
{isMutate: false}
and it won't mutate: github.com/jalal246/move-position#....It depends. 1-The scale of your data 2-Data mutation frequency 3-Data reference type.