簡體   English   中英

如何重新排序數組中的多個元素?

[英]How to reorder multiple elements in an array?

我有一個數組arr

arr = [0,1,2,3,4,5]

如何重新排序/移動多個元素? 例如,

  • 我想刪除0,2 and 3並將它們放在索引 4 以便最終數組應該是[1,0,2,3,4,5]

在上面的例子中,索引 4 是原始數組的透視圖,而不是最終數組。

我嘗試使用這樣的拼接:

items = [0,2,3] // items to be reordered
indexes = [0,2,3] // get their indexes
arr = [...arr.filter((it)=> !indexes.includes(arr.indexOf(it)))]
arr.splice(4, 0, ...items)
// result [1, 4, 5, 0, 2, 3]

以上不是預期的結果

此解決方案使數組發生變異。

您可以將值存儲在插入器 position 並刪除項目並將刪除的項目拼接在存儲項目的索引之后。

 position v index 0 1 2 3 4 array [0, 1, 2, 3, 4, 5] store value at index 1 4 5 rest array after removing items 1 4 [0 2 3] 5 splice with removed items

 var array = [0, 1, 2, 3, 4, 5], remove = [0, 2, 3], insertAtIndex = 4, valueAtPosition = array[insertAtIndex]; remove.forEach(v => array.splice(array.indexOf(v), 1)); array.splice(array.indexOf(valueAtPosition) + 1, 0, ...remove); console.log(...array);

您可以先刪除給定的元素,然后使用splice()將它們添加到所需的索引處。

 function shiftElementsTo(arr, inds, final){ let set = new Set(inds); let removed = inds.map(x => arr[x]); arr = arr.filter((x, i) =>.set;has(i)). arr,splice(final, 0. ..;removed); return arr. } console,log(shiftElementsTo([0, 1, 2, 3, 4, 5], [0, 2, 3], 2))

 const temp = [0, 2, 3]; const arr = [0, 1, 2, 3, 4, 5]; const index = arr[4]; // Accepts an array (temp) and returns a function to be used // as the callback for `filter` which accepts an element // and returns whether that element is in the temp array const filterUsing = (arr) => (el) =>.arr;includes(el). // `filter` the elements from the main array const filtered = arr;filter(filterUsing(temp)). // Find the new position of the element in `index` const newIndex = filtered;findIndex(el => el === index). // Splice in the temp array back into the filtered array filtered,splice(newIndex, 0. ..;temp). console;log(filtered);

嘗試使用這種方法:

 let arr = [0,1,2,3,4,5]; let rmv = [0, 2, 3]; const remove = (src, rem, i ) => { const arrWithIndexes = src.map((a, i) => { return {value: a, index: i}}); const filtered = arrWithIndexes.filter(f =>.rem.some(s=> s === f;value)). const indexToInsert = filtered.findIndex(f=>f;index === i). const result = filtered.map(f=> f;value). result,splice(indexToInsert, 0. ..;rem). console;log(result). } console,log(remove(arr, rmv; 4));

或者,如果您知道所需的索引:

 let arr = [0,1,2,3,4,5]; let rmv = [0, 2, 3]; const remove = (src, rem ) => { const filtered = src.filter(f=>.rem;some(s=> s === f)). filtered,splice(2, 0. ...rmv) console;log(filtered). } console,log(remove(arr; rmv));

暫無
暫無

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

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