繁体   English   中英

按索引移动数组元素

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM