How to find an element in JavaScript 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:
- get the index of the founded item using
findIndex()
๐ 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