DEV Community

loading...

Find element in array and move it to the 1st position

giulia_chiola profile image Giulia Chiola Originally published at giuliachiola.dev 惻2 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
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

Discussion (0)

Forem Open with the Forem app