EN
JavaScript - move element of array to the front
3
points
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.