配列の要素を見つけ、それを1番目の位置に移動します


確かにいくつかの方法を行うには、これは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