JavaScript数组排序顺序

时间:2017-07-21 08:12:58

标签: javascript arrays sorting

使用JavaScript(没有jQuery) - 我试图根据sortOrder属性显示9个项目的列表。问题是并非所有9个项目都在数组中。我需要从数组中检测到一个丢失的sortOrder,并在其位置显示一个空div,但我不知道从哪里开始。

以下是数据(注意缺少sortOrder'5'的数据):


"items":[  
  {  
     "name":"Lorem Ipsum",
     "sortOrder":1,
  },
  {  
     "name":"Dolor Sit",
     "sortOrder":2,
  },
  {  
     "name":"Amet Consectur",
     "sortOrder":3,
  },
  {  
     "name":"Adipising Elit",
     "sortOrder":4,
  },
  {  
    "name":"Lorem Dolor",
    "sortOrder":6,
  },
  {  
     "name":"Sit Amet",
     "sortOrder":7,
  },
  {  
     "name":"Elit Adipising",
     "sortOrder":8,
  },
  {  
     "name":"Dorem Consectur",
     "sortOrder":9,
  }
]

我想输出如下:

  • Lorem Ipsum
  • Dolor Sit
  • Amet Consectur
  • Adipising Elit
  • [EMPTY DIV]
  • Lorem Dolor
  • 坐在Amet
  • Elit Adipising
  • Dorem Consectur

但是,我得到了这个:

  • Lorem Ipsum
  • Dolor Sit
  • Amet Consectur
  • Adipising Elit
  • Lorem Dolor
  • 坐在Amet
  • Elit Adipising
  • Dorem Consectur
  • [EMPTY DIV]

2 个答案:

答案 0 :(得分:0)

这应该为你做,基本上你附加数组与对象参考&然后用任何东西填补遗失。

var data ={ "items":
           [  
    {  
       "name":"Lorem Ipsum",
       "sortOrder":1,
    },
    {  
       "name":"Dolor Sit",
       "sortOrder":2,
    },
    {  
       "name":"Amet Consectur",
       "sortOrder":3,
    },
    {  
       "name":"Adipising Elit",
       "sortOrder":4,
    },
    {  
      "name":"Lorem Dolor",
      "sortOrder":6,
    },
    {  
       "name":"Sit Amet",
       "sortOrder":7,
    },
    {  
       "name":"Elit Adipising",
       "sortOrder":8,
    },
    {  
       "name":"Dorem Consectur",
       "sortOrder":9,
    }
  ]
}

data.items.forEach((item,i,array) => { data.items['item:'+item.sortOrder] = item; });

var list = [1,2,3,4,5,6,7,8,9]
      .map(sortOrder => { return (data.items['item:'+sortOrder] || { name: 'Missing', sortOrder: sortOrder }); });
      
console.log(JSON.stringify(list,null,2));

答案 1 :(得分:0)

以下是一个选项如何执行此操作(如果您有小数组):

 var renderArr = function(arr, render) {
    var max = Math.max.apply(Math,arr.map(function(o){return o.sortOrder;}));

  for(var i = 1; i <= max; i++) {
    var el = arr.find(function(e) {     
        return e.sortOrder === i;
    });

    if(el) {
        render(el.name);
    }
    else {
        render("[EMPTY DIV]");
    }
  }
}

用法:

var ul = document.getElementsByTagName('ul')[0];

renderArr(items, function(content) {
    var li = document.createElement("li");
    li.innerHTML = content;  
    document.getElementsByTagName('ul')[0].appendChild(li);
});

以下是一个用法示例: https://jsfiddle.net/qyyq959c/