🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › shift
Array.prototype.shift() - JavaScript | MDN
The removed element from the array; undefined if the array is empty. The shift() method shifts all values to the left by 1 and decrements the length by 1, resulting in the first element being removed.
🌐
Programiz
programiz.com › javascript › library › array › shift
JavaScript Array shift()
let languages = ["English", "Java", "Python", "JavaScript"]; // removes the first element of the array let first = languages.shift(); console.log(first); console.log(languages); // Output: English // [ 'Java', 'Python', 'JavaScript' ]
🌐
Mimo
mimo.org › glossary › javascript › array-shift
JavaScript Array shift: Syntax, Usage, and Examples
Become a full-stack developer. Learn HTML, CSS, JavaScript, and React as well as NodeJS, Express, and SQL ... Master the language of the web. Learn variables, functions, objects, and modern ES6+ features ... The shift() method removes the first element from an array and returns that element.
🌐
GeeksforGeeks
geeksforgeeks.org › javascript › javascript-array-shift-method
JavaScript Array shift() Method - GeeksforGeeks
September 18, 2024 - Indices of the remaining elements are adjusted, decrementing by one to fill the gap left by the removed element. The function func() removes the first element from array using the shift() method.
🌐
TutorialsPoint
tutorialspoint.com › home › javascript › javascript array shift method
JavaScript Array Shift Method
September 1, 2008 - The JavaScript Array.shift() method is used to remove the first element from an array and returns the removed element. This method reduces the length of the original array by one. When we call this method on the empty array, it returns "undefined".
🌐
JavaScript Tutorial
javascripttutorial.net › home › javascript array methods › array.prototype.shift()
JavaScript Array shift() Method
November 6, 2024 - For example: let greetings = { 0: 'Hi', 1: 'Hello', 2: 'Howdy', length: 3, removeFirst() { return [].shift.call(this); }, }; const greeting = greetings.removeFirst(); console.log(greeting); console.log(greetings);Code language: JavaScript ...
🌐
Flexiple
flexiple.com › javascript › javascript-shift
Javascript Shift() - uses and limitations - Flexiple
Ex: You’re dealing with an array that’s sorted based on a parameter say point, and now you want the first element to be removed from the array. Javascript shift works best here as it removes the first character ensuring he doesn’t participate again and also returns the element so that it can be stored for reference.
🌐
freeCodeCamp
forum.freecodecamp.org › guide
How to use JavaScript Array.prototype.shift() - JavaScript Shift Explained with Examples
June 20, 2019 - The JavaScript array method .shift() will remove the first element from an array and return that value. This will also change the length of the array Syntax var array = [1, 2, 3, 4]; array.shift(); Description .shift(…
🌐
Codecademy
codecademy.com › docs › javascript › arrays › .shift()
JavaScript | Arrays | .shift() | Codecademy
June 9, 2022 - Removes and returns the first element of the array. All subsequent elements will shift down one place. ... Front-end engineers work closely with designers to make websites beautiful, functional, and fast. ... Learn how to use JavaScript — a powerful and flexible programming language for adding website interactivity.
Find elsewhere
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › JavaScript › Reference › Global_Objects › Array › unshift
Array.prototype.unshift() - JavaScript | MDN
const arr = [1, 2]; arr.unshift(0); // result of the call is 3, which is the new array length // arr is [0, 1, 2] arr.unshift(-2, -1); // the new array length is 5 // arr is [-2, -1, 0, 1, 2] arr.unshift([-4, -3]); // the new array length is 6 // arr is [[-4, -3], -2, -1, 0, 1, 2] arr.unshift([-7, ...
🌐
Educative
educative.io › answers › what-is-the-arrayshift-method-in-javascript
What is the array.shift() method in JavaScript?
array.shift() is a method that removes the first element from an​ array and shifts the array to the left by one position.
🌐
Jsremote
jsremote.jobs › tutorials › array-shift
What is the shift() method in JavaScript? | Web developer jobs
A good method for that purpose ... its value. For example, if you use Array.shift() to modify an array [“one”, “two”, “three”], you will get the “one” string returned....
Top answer
1 of 16
903

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

Note that the last return is simply for testing purposes: splice performs operations on the array in-place, so a return is not necessary. By extension, this move is an in-place operation. If you want to avoid that and return a copy, use slice.

Stepping through the code:

  1. If new_index is greater than the length of the array, we want (I presume) to pad the array properly with new undefineds. This little snippet handles this by pushing undefined on the array until we have the proper length.
  2. Then, in arr.splice(old_index, 1)[0], we splice out the old element. splice returns the element that was spliced out, but it's in an array. In our above example, this was [1]. So we take the first index of that array to get the raw 1 there.
  3. Then we use splice to insert this element in the new_index's place. Since we padded the array above if new_index > arr.length, it will probably appear in the right place, unless they've done something strange like pass in a negative number.

A fancier version to account for negative indices:

function array_move(arr, old_index, new_index) {
    while (old_index < 0) {
        old_index += arr.length;
    }
    while (new_index < 0) {
        new_index += arr.length;
    }
    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 purposes
};
    
// returns [1, 3, 2]
console.log(array_move([1, 2, 3], -1, -2));

Which should account for things like array_move([1, 2, 3], -1, -2) properly (move the last element to the second to last place). Result for that should be [1, 3, 2].

Either way, in your original question, you would do array_move(arr, 0, 2) for a after c. For d before b, you would do array_move(arr, 3, 1).

2 of 16
570

I like this method as it's concise and it just works.

function arraymove(arr, fromIndex, toIndex) {
    var element = arr[fromIndex];
    arr.splice(fromIndex, 1);
    arr.splice(toIndex, 0, element);
}

Note: always remember to check your array bounds.

The following snippet prints a few tests in console to show all combinations of fromIndex and toIndex (0..n, 0..n) work.

Run Snippet in jsFiddle

🌐
Vultr Docs
docs.vultr.com › javascript › standard-library › Array › shift
JavaScript Array shift() - Remove First Element | Vultr Docs
November 25, 2024 - ... let numbers = [1, 2, 3, 4, 5]; numbers.shift(); console.log(numbers.length); // Outputs: 4 Explain Code · In this example, removing one element from the numbers array reduces its length from 5 to 4.
🌐
Reality Ripple
udn.realityripple.com › docs › Web › JavaScript › Reference › Global_Objects › Array › shift
Array.prototype.shift() - JavaScript
It also displays the removed element: var myFish = ['angel', 'clown', 'mandarin', 'surgeon']; console.log('myFish before:', JSON.stringify(myFish)); // myFish before: ['angel', 'clown', 'mandarin', 'surgeon'] var shifted = myFish.shift(); console.log('myFish after:', myFish); // myFish after: ...
🌐
Scaler
scaler.com › home › topics › shift() in javascript
Shift() in JavaScript- Scaler Topics
July 5, 2022 - This article by Scaler Topics discusses the shift() method, which removes the first element from an array and returns the removed element.