Change the Position of an Array Element in JavaScript-Code Examples

Radu TM

Change the Position of an Array Element in JavaScript

JavaScript by Radu TM β€’ June 17, 2022

// create an array with emoji fruits
var fruits = ['🍎', '🍊', 'πŸ‹'];

// move the element at index 1 (🍊) to the end of the array
fruits.push(fruits.splice(1, 1)[0]);
// fruits is now ['🍎', 'πŸ‹', '🍊']

// move the element at index 2 (πŸ‹) to the beginning of the array
fruits.unshift(fruits.splice(2, 1)[0]);
// fruits is now ['πŸ‹', '🍎', '🍊']

0

17.976

Change the Position of an Array Element in JavaScript

JavaScript by Radu TM β€’ June 17, 2022

var fruits = ["🍎", "🍌", "🍊", "πŸ‹"];

//change the position of "🍎" to the end of the array
var apple = fruits.shift();
fruits.push(apple);

console.log(fruits); //["🍌", "🍊", "πŸ‹", "🍎"]

0

17.976

Related JavaScript Queries

Latest JavaScript Queries

Explore code examples by categories