Languages
[Edit]
EN

JavaScript - move element of array to the front

3 points
Created by:
Eshaal-Wilkinson
774

In this article, we would like to show you how to move an element of an array to the front in JavaScript.

Practical examples

In the below examples, we search for the element in array. If it is found, we move it to the front.

1. Using splice() method

// ONLINE-RUNNER:browser;

const element = 'c';
const array = ['a', 'c', 'd', 'b'];

const index = array.indexOf(element);
if (index !== -1) {
    const items = array.splice(index, 1);
    array.splice(0, 0, ...items);
}

console.log(array); // [ 'c', 'a', 'd', 'b' ]

2. Using sort() method

// ONLINE-RUNNER:browser;

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

const element = 'c';

array.sort((x) => x === element ? -1 : 0);

console.log(array); // [ 'c', 'a', 'd', 'b' ]

or:

// ONLINE-RUNNER:browser;

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

const element = 'c';

array.sort((x, y) => x === element ? -1 : y === element ? 1 : 0);

console.log(array); // [ 'c', 'a', 'd', 'b' ]

Note:

The performance of this solution may be low.

 

See also

  1. JavaScript - move element of array to the last position

References

  1. Array.prototype.sort() - JavaScript | MDN
  2. Conditional (ternary) operator - JavaScript | MDN
  3. Array.prototype.splice() - JavaScript | MDN

Alternative titles

  1. JavaScript - move array item to the front
  2. JavaScript - move element of array to the first position
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.
Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join