使用javascript数组调整和删除数字间隙

时间:2017-03-10 19:37:22

标签: javascript

我试图求助,然后删除此JavaScript数组中sortOrder属性的数字中的任何间隙。

例如:

p[0].sortOrder = 2; 
p[1].sortOrder = 12;
p[2].sortOrder = 4;
p[3].sortOrder = 8;
p[4].sortOrder = 6; 
p[5].sortOrder = 2; 
p[6].sortOrder = 8;   

应输出到:

p[0].sortOrder = 1; //used to be 2
p[1].sortOrder = 5; //used to be 12
p[2].sortOrder = 2; //used to be 4
p[3].sortOrder = 4; //used to be 8
p[4].sortOrder = 3; //used to be 6 
p[5].sortOrder = 1; //used to be 2
p[6].sortOrder = 4; //used to be 8   

这是它应该运行的功能。我无法绕过消除数字中的空白。

function restackSortOrder(p) {

    //Remove any gaps in numbers here while still retaining any duplicate numbers (which should stay grouped together).

    return p;
}

2 个答案:

答案 0 :(得分:5)

这是一个解决方案,在评论中有解释:



function resortStackorder(p) {
  var match = p.map(function(e) {                   //create array of sortOrder values
                return e.sortOrder;
              })
               .sort(function(a, b) {return a - b}) //sort the array numerically
               .filter(function(e, idx, array) {    //filter out duplicates
                 return e !== array[idx - 1];
               });

  p.forEach(function(e) {  //look up sortOrder's position in the match array
    e.sortOrder = match.indexOf(e.sortOrder) + 1;
  });
} //resortStackorder

var p = [
  {sortOrder: 2},
  {sortOrder: 12},
  {sortOrder: 4},
  {sortOrder: 8},
  {sortOrder: 6},
  {sortOrder: 2},
  {sortOrder: 8}
];

resortStackorder(p);

console.log(JSON.stringify(p));




答案 1 :(得分:1)

ES6版本,首先使用Set获取唯一项,然后使用Map将原始值与集合的索引进行映射:



let p = [{sortOrder: 2},{sortOrder: 12},{sortOrder: 4},{sortOrder: 8},{sortOrder: 6},{sortOrder: 2},{sortOrder: 8}];

let map = new Map([...new Set(p.map(o=>o.sortOrder))].sort((a,b)=>a-b).map((sO,ind)=>[sO,ind+1]));
for(let o of p)
	o.sortOrder = map.get(o.sortOrder);

console.log(JSON.stringify(p));