How to find an element in JavaScript and move it to the first position.

ยท

3 min read

Surely there are several way to do it, this is just one of them. Let me know if you know a better way to do it ๐Ÿ’ช๐Ÿป

To find an element into an array and move to be the first, you have to:

๐Ÿ“š The findIndex() method returns the index of the first element in the array that satisfies the provided testing function.

const arr = [1, 2, 3, '๐Ÿฑ', 4, 5, 6, 7, 8, 9 , 10]
const itemToFind = '๐Ÿฑ'

const foundIdx = arr.findIndex(el => el == itemToFind) // -> foundIdx = 3
  • remove the item in that specific position using splice()

๐Ÿ“š The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place.

arr.splice(foundIdx, 1)

// splice(start[, deleteCount[, item1[, item2[, ...]]]])
// start = foundIdx
// deleteCount = 1 = number of elements in the array to remove from start
  • add the item to the 1st position using unshift()

๐Ÿ“š The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array.

arr.unshift(itemToFind)

Output

console.log(arr)

// (11) ["๐Ÿฑ", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]

To sum up:

const arr = [1, 2, 3, '๐Ÿฑ', 4, 5, 6, 7, 8, 9 , 10]
const itemToFind = '๐Ÿฑ'

const foundIdx = arr.findIndex(el => el == itemToFind)
arr.splice(foundIdx, 1)
arr.unshift(itemToFind)

๐Ÿ“š More info

Moving Element In An Array From Index To Another