配列の要素を見つけ、それを1番目の位置に移動します
5366 ワード
確かにいくつかの方法を行うには、これは1つだけです.あなたがそれをするより良い方法を知っているならば、私に知らせてください💪🏻
要素を配列に探し、最初に移動するには、次のようにします.は、
特定の位置の項目を
は、
要素を配列に探し、最初に移動するには、次のようにします.
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
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
unshift()
を使用してアイテムを第1の位置に加えます📚 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)
出力console.log(arr)
// (11) ["🐱", 1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
まとめる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
Reference
この問題について(配列の要素を見つけ、それを1番目の位置に移動します), 我々は、より多くの情報をここで見つけました https://dev.to/giulia_chiola/find-element-in-array-and-move-it-to-the-1st-position-1mk5テキストは自由に共有またはコピーできます。ただし、このドキュメントのURLは参考URLとして残しておいてください。
Collection and Share based on the CC Protocol