You always pass failure on the way to success.

Mickey Rooney

Find element in array and move it to the first position

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

Edit this page on GitLab
Take me to the next post!