DEV Community

Giulia Chiola
Giulia Chiola

Posted on • Originally published at giuliachiola.dev

Find element in array and move it to the 1st 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
Enter fullscreen mode Exit fullscreen mode
  • 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
Enter fullscreen mode Exit fullscreen mode
  • 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)
Enter fullscreen mode Exit fullscreen mode

Output

console.log(arr)

// (11) ["🐱", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
Enter fullscreen mode Exit fullscreen mode

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)
Enter fullscreen mode Exit fullscreen mode

📚 More info

Moving Element In An Array From Index To Another

Top comments (0)