繁体   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