Rearrange the position of an element within an array

I'm struggling to find a solution for rearranging elements within an array. Consider the following:

var array = [ 'a', 'b', 'c', 'd', 'e'];

How can I create a function that moves the element 'd' to the left of 'b' ?

Or shifts 'a' to the right of 'c'?

After repositioning the elements, the indexes of the remaining elements need to be adjusted. The resulting array should look like this:

array = ['a', 'd', 'b', 'c', 'e']

Although seemingly straightforward, I am finding it challenging to implement.

Answer №1

If you're looking for a version available on npm, check out array-move. It's similar to this solution but not the exact implementation. Refer to its usage section for more information. An earlier version of this answer (which modified Array.prototype.move) can be found on npm at array.prototype.move.


I had quite good results using the following 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; // included for testing purposes
};

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

Note that the final return is specifically for testing: splice operates directly on the array, making a return unnecessary. Consequently, this move is an in-place operation. To avoid this and get a copy instead, utilize slice.

Going step by step through the code:

  1. If new_index surpasses the array length, it seems like we need to correctly pad the array with new undefineds. This snippet handles that by adding undefined to the array until reaching the right length.
  2. Next, in arr.splice(old_index, 1)[0], we remove the old element. The spliced method returns the removed element, which is within an array. In our example, this was [1]. Thus, taking the first index gives us the raw value of 1.
  3. We then use splice to place this element at the new_index position. Unless something strange like a negative number is provided, since we padded the array above if new_index > arr.length, it should be in the correct spot.

A more sophisticated version considering 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; // included for testing purposes
};
    
// outputs [1, 3, 2]
console.log(array_move([1, 2, 3], -1, -2));

This variation should properly handle scenarios like array_move([1, 2, 3], -1, -2) (moving the last element to the second-to-last position). The result should be [1, 3, 2].

In your original question, array_move(arr, 0, 2) would move a after c. To place d before b, you would do array_move(arr, 3, 1).

Answer №2

This approach is great because it's straightforward and effective.

function rearrangeArray(arr, startIdx, endIdx) {
    var item = arr[startIdx];
    arr.splice(startIdx, 1);
    arr.splice(endIdx, 0, item);
}

Remember to always double-check your array boundaries.

The code snippet below demonstrates various test cases in the console for different combinations of startIdx and endIdx (0..n, 0..n).

Test Snippet on jsFiddle

Answer №3

Just stumbled upon this gem on JSPerf...

Array.prototype.move = function(from, to) {
    this.splice(to, 0, this.splice(from, 1)[0]);
};

It's a neat little trick, but for better performance (especially with small data sets), consider trying out...

 Array.prototype.move2 = function(pos1, pos2) {
    // local variables
    var i, tmp;
    // convert input parameters to integers
    pos1 = parseInt(pos1, 10);
    pos2 = parseInt(pos2, 10);
    // if positions are different and within array bounds
    if (pos1 !== pos2 && 0 <= pos1 && pos1 <= this.length && 0 <= pos2 && pos2 <= this.length) {
      // save the element at position 1
      tmp = this[pos1];
      // shift elements up or down accordingly to move element
      if (pos1 < pos2) {
        for (i = pos1; i < pos2; i++) {
          this[i] = this[i + 1];
        }
      }
      else {
        for (i = pos1; i > pos2; i--) {
          this[i] = this[i - 1];
        }
      }
      // place the saved element at destination position
      this[pos2] = tmp;
    }
  }

All credits go to Richard Scarrott. It outperforms the splice method in small data sets according to this benchmark, although it's noticeably slower with larger data sets as pointed out by Darwayne.

Answer №4

The splice() method is used to add or remove items from an array, and it also returns the removed item(s).

Keep in mind that this method will modify the original array. /w3schools/

Array.prototype.move = function(from,to){
  this.splice(to,0,this.splice(from,1)[0]);
  return this;
};

var arr = [ 'a', 'b', 'c', 'd', 'e'];
arr.move(3,1);//["a", "d", "b", "c", "e"]


var arr = [ 'a', 'b', 'c', 'd', 'e'];
arr.move(0,2);//["b", "c", "a", "d", "e"]

Since the function can be chained together, you can also do this:

alert(arr.move(0,2).join(','));

Check out the demo here

Answer №5

Here is my two cents on the topic: The code provided is easy to read, effective in performance, and does not generate new arrays.

function repositionArrayItems(array, fromIndex, toIndex) {
  if (toIndex === fromIndex) return array;

  var targetElement = array[fromIndex];                         
  var incrementValue = toIndex < fromIndex ? -1 : 1;

  for (var i = fromIndex; i != toIndex; i += incrementValue){
    array[i] = array[i + incrementValue];
  }
  array[toIndex] = targetElement;
  return array;
}

Answer №6

Presenting a concise ES6 solution featuring an optional parameter on.

if (typeof Array.prototype.transfer === "undefined") {
  Array.prototype.transfer = function(start, end, on = 1) {
    this.splice(end, 0, ...this.splice(start, on))
  }
}

Inspired by the initial concept put forth by wizkiddo

The variable on represents the quantity of elements to relocate from position start.

Additionally, here is a streamlined version that supports chaining:

if (typeof Array.prototype.transfer === "undefined") {
  Array.prototype.transfer = function(start, end, on = 1) {
    return this.splice(end, 0, ...this.splice(start, on)), this
  }
}

[7, 8, 9, 10, 11].transfer(3, 0, 2) // => [10, 11, 7, 8, 9]

To prevent polluting prototypes, consider using a standalone utility function instead:

function transferArray(arr, start, end, on = 1) {
  return arr.splice(end, 0, ...arr.splice(start, on)), arr
}

transferArray([7, 8, 9, 10, 11], 3, 0, 2) // => [10, 11, 7, 8, 9]

For non-destructive operations, a pure function can be applied without modifying the original array:

function transferredArray(arr, start, end, on = 1) {
  return arr = arr.slice(), arr.splice(end, 0, ...arr.splice(start, on)), arr
}

This comprehensive approach encompasses various scenarios seen across different solutions.

Answer №7

Inspired by @Reid, I came up with an interesting concept of pushing a placeholder object instead of moving the actual item in an array to maintain its size. This approach simplifies calculations and allows for unique identification later on when searching. The reason this method works is that two objects are not considered equal unless they refer to the same object.

({}) == ({}); // false

Here's a function designed to move an object within an array from a source index to a destination index. It can be added to the Array.prototype if necessary.

function moveObjectAtIndex(array, sourceIndex, destIndex) {
    var placeholder = {};
    // Replace the object at the source index with a placeholder object to maintain array length
    var objectToMove = array.splice(sourceIndex, 1, placeholder)[0];
    // Insert the object at the destination index
    array.splice(destIndex, 0, objectToMove);
    // Remove the temporary placeholder object
    array.splice(array.indexOf(placeholder), 1);
}

Answer №8

This solution is inspired by @Reid's approach, with some modifications:

  • I have opted not to alter the Array prototype.
  • If an item is moved beyond the array bounds to the right, it will shift to the far-right position without creating any undefined elements.

Here is the revised function:

function move(array, oldIndex, newIndex) {
    if (newIndex >= array.length) {
        newIndex = array.length - 1;
    }
    array.splice(newIndex, 0, array.splice(oldIndex, 1)[0]);
    return array;
}

Unit tests for the ArrayHelper:

describe('ArrayHelper', function () {
    it('Move right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 0, 1);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    })
    it('Move left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 0);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the left', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, -2);
        assert.equal(array[0], 2);
        assert.equal(array[1], 1);
        assert.equal(array[2], 3);
    });
    it('Move out of bounds to the right', function () {
        let array = [1, 2, 3];
        arrayHelper.move(array, 1, 4);
        assert.equal(array[0], 1);
        assert.equal(array[1], 3);
        assert.equal(array[2], 2);
    });
});

Answer №9

To optimize your code, consider incorporating basic calculus to develop a versatile function that can rearrange elements within an array seamlessly.

In the world of JavaScript, the implementation might resemble the following:

function myMagicFunction (targetArray, startIndex, destinationIndex) { 

    selectedElement = targetArray[startIndex]; 
    gap = (destinationIndex - startIndex) / Math.abs(destinationIndex - startIndex); 

    for (currentElement = startIndex; currentElement != destinationIndex; currentElement += gap){ 
        targetArray[currentElement] = targetArray[currentElement + gap]; 
    } 

    targetArray[destinationIndex] = selectedElement; 

}

For a more detailed explanation on "moving array elements," visit the "Gloommatter" website at the link below:

https://web.archive.org/web/20121105042534/http://www.gloommatter.com:80/DDesign/programming/moving-any-array-elements-universal-function.html

Answer №10

I have created a non-changeable ES6 solution inspired by the answer provided by @Merc in this discussion:

const rearrangeArrayItems = (arr, startIdx, endIdx) => {
  if (startIdx === endIdx) return arr;

  const newArr = [...arr];

  const targetItem = newArr[startIdx];
  const incrementalValue = endIdx < startIdx ? -1 : 1;

  for (let i = startIdx; i !== endIdx; i += incrementalValue) {
    newArr[i] = newArr[i + incrementalValue];
  }

  newArr[endIdx] = targetItem;

  return newArr;
};

The names of the variables can be shortened, but I have used descriptive ones for clarity.

Answer №11

By the year 2022, this TypeScript tool will be capable of working in conjunction with a unit test.

export const arrayMove = <T>(arr: T[], fromIndex: number, toIndex: number) => {
  const newArr = [...arr];
  newArr.splice(toIndex, 0, newArr.splice(fromIndex, 1)[0]);
  return newArr;
};

const testArray = ['1', '2', '3', '4'];

describe('arrayMove', () => {
  it('should move array item to toIndex', () => {
    expect(arrayMove(testArray, 2, 0)).toEqual(['3', '1', '2', '4']);
    expect(arrayMove(testArray, 3, 1)).toEqual(['1', '4', '2', '3']);
    expect(arrayMove(testArray, 1, 2)).toEqual(['1', '3', '2', '4']);
    expect(arrayMove(testArray, 0, 2)).toEqual(['2', '3', '1', '4']);
  });
});

Answer №12

To efficiently move an element within an array, a useful approach involves utilizing the splice() method. Initially, this function removes the desired item from its current index in the array. Subsequently, by employing splice() once more, the removed item can be seamlessly inserted into the specified target index.

const array = ['a', 'b', 'c', 'd', 'e']

const newArray = moveItem(array, 3, 1) // transferring element from index 3 to index 1

function moveItem(arr, fromIndex, toIndex){
  let itemRemoved = arr.splice(fromIndex, 1) // capturing the removed item as an array
  arr.splice(toIndex, 0, itemRemoved[0]) // placing itemRemoved into the target index
  return arr
}

console.log(newArray)

You can access a concise explanation of the splice() function here

Answer №13

To change the order of elements in an array, one method is to create a new array with the desired sequence using the slice operation.

Here's an illustration:

const originalArray = [ 'apple', 'banana', 'cherry', 'date', 'elderberry'];
const newArray = originalArray.slice(0,1).concat(['date']).concat(originalArray.slice(2,4)).concat(originalArray.slice(4));
  • Slicing from index 0 to 1 gives you ['apple']
  • Slicing from index 2 to 4 gives you ['banana', 'cherry']
  • Slicing from index 4 (till end) gives you ['elderberry']

Answer №14

A different approach in pure JavaScript using ES6 array spread operator but with no changes to the original array

const switchOrder = (arr, startIdx, endIdx) => {
  const smallerIdx = Math.min(startIdx, endIdx);
  const largerIdx = Math.max(startIdx, endIdx);

  return [
    ...arr.slice(0, smallerIdx),
    ...(startIdx < endIdx
      ? arr.slice(smallerIdx + 1, largerIdx + 1)
      : []),
    arr[startIdx],
    ...(startIdx > endIdx
      ? arr.slice(smallerIdx, largerIdx)
      : []),
    ...arr.slice(largerIdx + 1),
  ];
}

// output will be ['a', 'c', 'd', 'e', 'b', 'f']
console.log(switchOrder(['a', 'b', 'c', 'd', 'e', 'f'], 1, 4))
      
 

Answer №16

To achieve an immutable move operation (one that does not alter the original array), I modified @Reid's approved solution by using Object.assign to make a duplicate of the array before performing the splice.

Array.prototype.immutableMove = function (old_index, new_index) {
  var copy = Object.assign([], this);
  if (new_index >= copy.length) {
      var k = new_index - copy.length;
      while ((k--) + 1) {
          copy.push(undefined);
      }
  }
  copy.splice(new_index, 0, copy.splice(old_index, 1)[0]);
  return copy;
};

You can see this in action on this jsfiddle link.

Answer №17

TypeScript Version

Found this implementation on @Merc's answer. I appreciate it because it doesn't create new arrays and instead modifies the existing array directly. I made some updates for ES6 compatibility and added type declarations.

export function rearrangeArrayItem<T>(arr: T[], startIndex: number, targetIndex: number): T[] {
    if (targetIndex === startIndex) {
        return arr;
    }
    const itemToMove = arr[startIndex];
    const step = targetIndex < startIndex ? -1 : 1;

    for (let i = startIndex; i !== targetIndex; i += step) {
        arr[i] = arr[i + step];
    }
    arr[targetIndex] = itemToMove;
    return arr;
}

Answer №18

    Enhancing the Array object with custom methods for moving elements up and down is a useful feature in JavaScript. With these functions, you can easily manipulate the order of elements within an array based on specific criteria.
    
    Let's take a look at an example using the customized 'moveUp' and 'moveDown' methods. We start with an array containing four elements: 'banana', 'curyWurst', 'pc', and 'remembaHaruMembaru'. Initially, they are displayed in their original order.
    
    After calling the 'moveDown' method on the third element ('pc'), we see that it has been moved down one position in the array. The updated sequence is shown in the alert message.
    
    Next, by using the 'moveUp' method on the same element ('pc'), we reverse the movement and bring it back to its previous position. Once again, the modified array arrangement is displayed in an alert box.

http://plnkr.co/edit/AbcDefGhiJklMnoPqrSt?p=preview

Answer №19

Here's a method to achieve immutability when moving elements within an array. This approach accounts for negative numbers and prioritizes reducing potential bugs over performance optimizations compared to directly modifying the original array.

const array = [7, 8, 9];
const rearrangeElement = (arr, start, end) => {
  const clone = [...arr];
  const elementToMove = clone.splice(start, 1)[0];
  clone.splice(end, 0, elementToMove);
  return clone;
};

console.log(rearrangeElement(array, 0, 2))
// > [8, 9, 7]
console.log(rearrangeElement(array, -1, -3))
// > [9, 7, 8] 

Answer №20

Reposition an element in an array to the beginning

For example, move the element 'd' to the first position:

let arr = [ 'a', 'b', 'c', 'd', 'e'];
arr = [...arr.filter(item => item === 'd'), ...arr.filter(item => item !== 'd')];
console.log(arr);

Answer №21

While it's often cautioned against playing with the Array prototype, I've gathered insights from various sources and crafted a modern Javascript solution:

    Object.defineProperty(Array.prototype, 'shiftArray', {
        enumerable: false,
        value: function (old_index, new_index) {
            var copy = Object.assign([], this)
            if (new_index >= copy.length) {
                var diff = new_index - copy.length;
                while ((diff--) + 1) { copy.push(undefined); }
            }
            copy.splice(new_index, 0, copy.splice(old_index, 1)[0]);
            return copy
        }
    });

    // Example of how to use it
    myArray=[0, 1, 2, 3, 4];
    myArray=myArray.shiftArray(2, 4);
    console.log(myArray);
    // Resulting array: 0, 1, 3, 4, 2

I hope this snippet proves helpful for others!

Answer №22

Not everyone may be fond of comma expressions, but there's a concise one-liner provided here for creating a new copy in a pure expression:

const relocate = (start, end, ...arr) => (arr.splice(end, 0, ...arr.splice(start, 1)), arr)

An optimized version is available for cases where no relocation is required, ensuring the input array remains untouched and suitable for immutable operations:

const relocate = (start, end, ...arr) => 
    start === end 
    ? arr 
    : (arr.splice(end, 0, ...arr.splice(start, 1)), arr)

To execute either function:

const rearranged = relocate(startIndex, targetIndex, ...array)

This implementation utilizes spreading to create a fresh duplicate. Introducing a fixed arity 3 relocate would compromise the single-expression feature, non-destructive behavior, or efficiency gained from splice. It serves more as an illustrative example meeting specific criteria rather than a recommended choice for practical applications.

Answer №23

def move_items(from_index, to_index, *items):
    if from_index == to_index:
        return items
    else:
        item = items[from_index]
        items = list(items)
        items.pop(from_index)
        items.insert(to_index, item)
        return tuple(items)

moved_items = move_items(1, 3, 'apple', 'banana', 'cherry')
print(moved_items)

Answer №24

Initially, I believed this to be a swapping issue, but upon further inspection, it appears not to be the case. Here is my concise solution in just one line:

const rearrange = (arr, fromIndex, toIndex) => arr.map((item, i) => i === toIndex ? arr[fromIndex] : (i >= Math.min(fromIndex, toIndex) && i <= Math.max(fromIndex, toIndex) ? arr[i + Math.sign(toIndex - fromIndex)] : item));

Below is a brief test of this function using a small example array:

let sampleArray = ['apple', 'banana', 'cherry', 'date', 'elderberry'];
console.log(rearrange(sampleArray, 0, 2)); // [ 'banana', 'cherry', 'apple', 'date', 'elderberry' ]
console.log(rearrange(sampleArray, 1, 3)); // [ 'apple', 'cherry', 'date', 'banana', 'elderberry' ]
console.log(rearrange(sampleArray, 2, 4)); // [ 'apple', 'banana', 'date', 'elderberry', 'cherry' ]
console.log(rearrange(sampleArray, 2, 0)); // [ 'cherry', 'apple', 'banana', 'date', 'elderberry' ]
console.log(rearrange(sampleArray, 3, 1)); // [ 'apple', 'date', 'banana', 'cherry', 'elderberry' ]
console.log(rearrange(sampleArray, 4, 2)); // [ 'apple', 'banana', 'elderberry', 'cherry', 'date' ]
console.log(rearrange(sampleArray, 4, 0)); // [ 'elderberry', 'apple', 'banana', 'cherry', 'date' ]

Answer №25

Here's a straightforward technique utilizing the splice function

Array.prototype.moveToBeginning = function(index) {
    this.splice(0, 0, this.splice(index, 1)[0]);
    return this;
  };

Answer №26

I find joy in using immutable and functional one-liners!

const swapArrayIndex = (arr, a, b) => (
  a < b 
    ? [...arr.slice(0, a), ...arr.slice(a + 1, b + 1), arr[a], ...arr.slice(b + 1)] 
    : [...arr.slice(0, b), arr[a], ...arr.slice(b, a), ...arr.slice(a + 1)]
);

Answer №27

After experimenting with different approaches, I found that combining two techniques allowed for smoother movement over both short and long distances. While my results are consistently good, I believe there is room for improvement by someone more skilled in this area to optimize the performance based on varying sizes.

For moving objects short distances, I discovered that alternative methods were significantly faster (x10) compared to using splice. However, this efficiency may vary depending on the length of the array, especially evident with larger arrays.

function ArrayMove(array, from, to) {
    if ( Math.abs(from - to) > 60) {
        array.splice(to, 0, array.splice(from, 1)[0]);
    } else {
        // works better when we are not moving things very far
        var target = array[from];
        var inc = (to - from) / Math.abs(to - from);
        var current = from;
        for (; current != to; current += inc) {
            array[current] = array[current + inc];
        }
        array[to] = target;    
    }
}

https://web.archive.org/web/20181026015711/https://jsperf.com/arraymove-many-sizes

Answer №28

Developed with an object-oriented approach, easily readable, fully debuggable, without causing mutations, and thoroughly tested.

class Sorter {
    sortItem(array, fromIndex, toIndex) {
        const reduceItems = () => {
            const startingItems = array.slice(0, fromIndex);
            const endingItems = array.slice(fromIndex + 1);
            return startingItems.concat(endingItems);
        }
        const addMovingItem = (movingItem, reducedItems) => {
            const startingNewItems = reducedItems.slice(0, toIndex);
            const endingNewItems = reducedItems.slice(toIndex);
            const newItems = startingNewItems.concat([movingItem]).concat(endingNewItems);
            return newItems;
        }
        const movingItem = array[fromIndex];
        const reducedItems = reduceItems();
        const newItems = addMovingItem(movingItem, reducedItems);
        return newItems;
    }
}

const sorter = new Sorter();
export default sorter;
import sorter from 'src/common/Sorter';

test('sortItem first item forward', () => {
    const startingArray = ['a', 'b', 'c', 'd'];
    const expectedArray = ['b', 'a', 'c', 'd'];
    expect(sorter.sortItem(startingArray, 0, 1)).toStrictEqual(expectedArray);
});
test('sortItem middle item forward', () => {
    const startingArray = ['a', 'b', 'c', 'd'];
    const expectedArray = ['a', 'c', 'b', 'd'];
    expect(sorter.sortItem(startingArray, 1, 2)).toStrictEqual(expectedArray);
});
test('sortItem middle item backward', () => {
    const startingArray = ['a', 'b', 'c', 'd'];
    const expectedArray = ['a', 'c', 'b', 'd'];
    expect(sorter.sortItem(startingArray, 2, 1)).toStrictEqual(expectedArray);
});
test('sortItem last item backward', () => {
    const startingArray = ['a', 'b', 'c', 'd'];
    const expectedArray = ['a', 'b', 'd', 'c'];
    expect(sorter.sortItem(startingArray, 3, 2)).toStrictEqual(expectedArray);
});

Answer №29

There are various ways to move an element in an array from one position to another without mutating the original array. Here, I have demonstrated 3 different approaches:

Using splice Method with Quadratic Time Complexity - O(n^2)

function moveArrayElement(arr, oldIndex, newIndex) {
  const copiedArr = [...arr];
  const length = copiedArr.length;
  
  if (oldIndex !== newIndex && length > oldIndex && length > newIndex) {
    copiedArr.splice(newIndex, 0, copiedArr.splice(oldIndex, 1)[0]);
  }
  
  return copiedArr;
}

moveArrayElement([1,2,3,4], 0, 3) // [2,3,4,1]

Using flatMap Method with Linear Time Complexity - O(n)

function moveArrayElement(arr, oldIndex, newIndex) {
    const length = arr.length;
    const itemToMove = arr[oldIndex]

    if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
        return arr;
    }

    return arr.flatMap((item, index) => {
        if (index === oldIndex) return [];
        if (index === newIndex) return oldIndex < newIndex ? [item, itemToMove] : [itemToMove, item];
        return item;
    })
}

moveArrayElement([1,2,3,4], 0, 3) // [2,3,4,1]

Using reduce Method with Linear Time Complexity - O(n)

function moveArrayElement(arr, oldIndex, newIndex) {
    const length = arr.length;
    const itemToMove = arr[oldIndex]

    if (oldIndex === newIndex || oldIndex > length || newIndex > length) {
        return arr;
    }

    return arr.reduce((acc, item, index) => {
        if (index === oldIndex) return acc;
        if (index === newIndex) return oldIndex < newIndex ? [...acc, item, itemToMove] : [...acc, itemToMove, item];
        return [...acc, item];
    }, [])
}

moveArrayElement([1,2,3,4], 0, 3) // [2,3,4,1]

For more information, you can also refer to this gist: Move an array element from one array position to another

Answer №30

ShuffleArray.js

Description

A JavaScript function that shuffles elements within an array and returns the shuffled array.

Syntax

shuffleArray(array);

Parameters

array: The array to be shuffled.

Usage

array = ["apple", "banana", "cherry", "date", "fig"];

shuffleArray(array); // returns a shuffled version of the original array

array; // displays the shuffled array

Polyfill

Array.prototype.shuffle || Object.defineProperty(Array.prototype, "shuffle", {
    value: function (array) {
        var
        arr = this,
        currentIndex = arr.length,
        temporaryValue, randomIndex;

        while (0 !== currentIndex) {
            randomIndex = Math.floor(Math.random() * currentIndex);
            currentIndex -= 1;
            
            temporaryValue = arr[currentIndex];
            arr[currentIndex] = arr[randomIndex];
            arr[randomIndex] = temporaryValue;
        }
        
        return arr;
    }
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Enhance the appearance of TreeGrid nodes by customizing the icons according to the data within

Currently, I am working with the MUI DataGridPro component and my goal is to customize the icons of the TreeGrid nodes based on the data. This image illustrates what I hope to achieve: https://i.stack.imgur.com/nMxy9.png Despite consulting the official do ...

Error: Unsupported Media Type when attempting to send JSON data from an AngularJS frontend to a Spring controller

Below is the controller function code snippet @RequestMapping(value = "/logInChecker", method = RequestMethod.POST, consumes = {"application/json"}) public @ResponseBody String logInCheckerFn(@RequestBody UserLogData userLogData){ Integer user ...

Transform the post data into a JSON string within the controller

Hello everyone, I have a sample table that I want to share: <table class="table table-bordered" width="100%" cellspacing="0" id="tableID"> <thead> <tr> <th>A</th> <th>B</th> <th>C< ...

Using a dynamic HTML interface, select from a vast array of over 50,000 values by leveraging the power

I am working on a project that includes a multiselect option with over 50,000 records. We are using AJAX to fetch data from the server based on user searches, which works fine. However, when a user tries to select all records by clicking the "check all" ...

Initiating a conversation using a greeting in the Javascript bot framework

I am looking to initiate a multi-level, multiple choice dialog from the welcome message in the Bot Framework SDK using JavaScript. I have a main dialog (finalAnswerDialog) that utilizes LUIS for predicting intents, and a multi-level, multiple choice menu d ...

D3.js: Unveiling the Extraordinary Tales

I'm currently working on a project that requires me to develop a unique legend featuring two text values. While I have successfully created a legend and other components, I am facing difficulties in achieving the desired design. Specifically, the cur ...

Entering numerous numerical values across a variety of input fields

My website currently has a form with 6 input fields where visitors need to enter a 6 digit code. To make it easier for them, I want to allow users to simply paste the code we provide into the first input field and have the remaining digits automatically po ...

What could be causing me to receive 'undefined' and an empty array[] when using Promise.all with JavaScript async operations making calls to Azure APIs?

In my personal project utilizing Azure AI APIs and Node.js/Express,, I am working on handling a get request to a /viewText route by extracting text and key phrases from an uploaded image/document. Below is the code snippet that should log this data to the ...

Error encountered in Ubuntu while attempting to run a Python script within a Node.js/Express application: spawn EACCES

Recently, I set up a node.js server to run a python script using the python-shell . However, after migrating from Windows to Ubuntu, an EACCES error has been persistently popping up. Despite my attempts to adjust permissions and troubleshoot, I haven' ...

In Nodejs, there is a way to determine the size of a document stored

I have a question: How can I determine the size of a cursor, in terms of kilobytes (KB), without actually fetching it? I've come across various sources, such as this post on Stack Overflow, but I don't want to retrieve the query result just to f ...

Is there a way to call class methods from external code?

I am seeking clarification on Class files. Below is an example of a Class that I have: class CouchController { constructor(couchbase, config) { // You may either pass couchbase and config as params, or import directly into the controller ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

verifying an email address through firebase using the verifyPasswordResetCode method

Currently in the process of setting up firebase authentication. Instead of relying on firebase's default pages for recovery password and email verification, I want to handle these processes directly on my website. To customize the recovery steps: U ...

The warning message from npm indicates a lack of permission to write to the specified directory, `/usr/local/lib

Important: For security reasons, please avoid using the suggested solution and opt for the top-voted answer instead! Query: I am attempting to execute the installation of Monaca with this command. npm install -g monaca However, immediately encountering ...

Guide to including configuration settings in locals for Sails.js

Currently working on a webapp with Sails.js, I am looking for ways to set up different configurations for development and production modes. Initially, I attempted to store the configuration key in config/local.js, but unfortunately, it did not yield the de ...

The form submission button fails to function when the onsubmit function returns false

When submitting, I check two fields. If one of the two fields is checked, then I return true; otherwise, I return false. The issue I'm facing is that even when I check one of the checkboxes, the submit button does not seem to work (I use console.log() ...

Encountering issues importing Ace Document Object in a Vue webpack project?

In my Vue and Webpack project, I am trying to incorporate the Ace editor. My goal is to associate each file with a single instance of an Ace Document. To achieve this, I followed the default import method: import Ace from 'ace-builds' When atte ...

Randomizing jQuery for duplicated HTML/jQuery elements

I'm facing a challenge with my jQuery and HTML scripts. I have a dropdown menu where a randomly generated number is displayed in the supplies field (voorraad) based on the selected option. However, when I clone this field using the add button, the fun ...

What steps can I take to personalize Material UI within a React application?

As someone who is new to this UI framework and React, I have been tasked with developing an application that requires more design patterns. I specifically chose a framework that does not depend on jQuery code. However, I am facing challenges when it comes ...

Looking for a solution to resolve a "repeated definition" issue

To better illustrate the issue I am facing, here is a simplified toy code example: stuff.h: #ifndef STUFF #define STUFF int a; int testarr[]={1,2,3}; #endif fcn.h: #include "stuff.h" int b[]={5,6,7}; void fcn(); main.h: #include "stuff.h" #include ...