[英]Shifting array element by indexes
我一直在嘗試解決該程序。 我有一個看起來像這樣的對象列表。 根據元素的索引位置將元素添加到數組中。
let A = {index: 0}
let B = {index: 0}
let C = { index: 2}
let D = {index: 2}
let E = { index: 1}
因此,如果將A推入數組,它將接管數組索引位置0。但是,當B推入數組時,它將接管索引位置。 [B,A],依此類推。 有點像先進入,先出來,除了左移。 但是,我想做這樣的事情。 [B,A,C],我想將D添加到C的索引位置。[B,A,D,C]。 A在索引位置1。我想在索引1處插入E。[B,E,A,D,C]
function insert(array, el) {
let pos = 0;
while(array[pos].index < el.index) pos++;
array.splice(pos, 0, el);
}
只需執行插入排序並使用splice
添加元素即可。
您可以簡單地拼接數組以在所需索引處添加對象。
var a = { index: 0, value: 'a' }, b = { index: 0, value: 'b' }, c = { index: 2, value: 'c' }, d = { index: 2, value: 'd' }, e = { index: 1, value: 'e' }, array = []; function add(array, object) { array.splice(object.index, 0, object); } add(array, a); add(array, b); add(array, c); add(array, d); add(array, e); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
您可以使用函數splice
並檢查index屬性以在特定位置插入。
如果index屬性不存在,則在最后推送對象。
var decorate = (arr) => { arr.insertByIndex = (...objs) => { objs.forEach(obj => { if (!isNaN(obj.index)) arr.splice(obj.index, 0, obj); else arr.push(obj); }); } return arr; }; let A = {index: 0, desc: 'A'}; let B = {index: 0, desc: 'B'}; let C = {index: 2, desc: 'C'}; let D = {index: 2, desc: 'D'}; let E = {index: 1, desc: 'E'}; var array = decorate([]); array.insertByIndex(D, A, C, B, E); console.log(array);
.as-console-wrapper { max-height: 100% !important; top: 0; }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.