簡體   English   中英

將數組的一個元素移到末尾position,另一個移到前面position,其余的應該在剩余的position

[英]Move array's one element to the end position and another one to the front position, and the others should be in the remaining position

我有數組:['B'、'D'、'I'、'M'、'其他'、'T'、'U']。

我想按順序對其進行排序:['T', 'B', 'D', 'I', 'M', 'U', 'Other']。

如何使用 JavaScript 實現它?

您是否只是希望這個精確的數組將兩個值移動到數組中的其他位置? 如果是這樣,你可以這樣做,假設你的原始數組被稱為arr

let startSplice = arr.splice(5,1)
let endSplice = arr.splice(4,1)

arr.unshift(startSplice[0])
arr.push(endSplice[0])

但我不會真的稱之為“排序”。 在數組上下文中排序通常意味着您已經為數組中的每個元素設置了您希望數組順序的規則,並且您可能會遇到需要使用這些規則排序的各種 arrays。

如果你的規則只是“如果我遇到一個‘T’,就把它放在數組的開頭”和“如果我遇到‘其他’,就把它放在數組的末尾”,那么你可以這樣做:

arr.sort((a,b) => {
    if (a === 'Other') {
        return 1
    } else if (a === 'T') {
        return -1
    } else if (b === 'Other') {
        return -1
    } else if (b === 'T') {
        return 1
    } else {
        return 0
    }
})

您可以將 object 與訂單一起使用並對數組進行排序。

 const array = ['B', 'D', 'I', 'M', 'Other', 'T', 'U'], order = { T: -1, Other: Number.MAX_VALUE }; array.sort((a, b) => (order[a] || 0) - (order[b] || 0)); console.log(...array);

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM