统一数组结构

6ss1mwsb  于 2021-06-25  发布在  Mysql
关注(0)|答案(2)|浏览(312)

我需要你的帮助,我有一个数组,其中包含每个月(12个月)执行的任务数,如下所示:

[      
  ["Ilhem", "Ben Salah", 4, 1],     
  ["Ilhem", "Ben Salah", 3, 2],
  ["Ilhem", "Ben Salah", 3, 3],
  ["Ilhem", "Ben Salah", 3, 4],
  ["Sghaier", "Mahmoud", 1, 1]
]

现在我需要一个这样的数组:

[
["Ilhem", "Ben Salah", 4, 1],
["Ilhem", "Ben Salah", 0, 2],
["Ilhem", "Ben Salah", 0, 3],
["Ilhem", "Ben Salah", 0, 4],
["Ilhem", "Ben Salah", 0, 5],
["Ilhem", "Ben Salah", 0, 6],
["Ilhem", "Ben Salah", 0, 7],
["Ilhem", "Ben Salah", 0, 8],
["Ilhem", "Ben Salah", 0, 9],
["Ilhem", "Ben Salah", 0, 10],
["Ilhem", "Ben Salah", 0, 11],
["Ilhem", "Ben Salah", 0, 12],
["Sghaier", "Mahmoud", 7, 1],
["Sghaier", "Mahmoud", 0, 2],
["Sghaier", "Mahmoud", 0, 3],
["Sghaier", "Mahmoud", 0, 4],
["Sghaier", "Mahmoud", 0, 5],
["Sghaier", "Mahmoud", 0, 6],
["Sghaier", "Mahmoud", 0, 7],
["Sghaier", "Mahmoud", 0, 8],
["Sghaier", "Mahmoud", 0, 9],
["Sghaier", "Mahmoud", 0, 10],
["Sghaier", "Mahmoud", 0, 11],
["Sghaier", "Mahmoud", 0, 12]

]
如何进行请我很困惑。

9q78igpj

9q78igpj1#

首先创建一个使用名称作为键的对象和一个子对象,该子对象使用月份号作为键为该名称存储现有月份的数组
然后使用1-12之间的循环,查看该名称是否存在月份,如果不存在,则填写缺少的项

function fillMonthHoles(data) {
  var groupByName = {}
  data.forEach(function(arr) {
    var baseArr = arr.slice(0, 2), nameKey = baseArr.join('|');
    this[nameKey] = this[nameKey] || {baseArr : baseArr};   
    this[nameKey][arr[3]] = arr;
  }, groupByName);

  return Object.keys(groupByName).reduce(function(a, key) {
    var baseArr = groupByName[key].baseArr
    for (var i = 1; i < 13; i++) {
      var arr = groupByName[key][i];
      if (!arr) {
        arr = baseArr.slice().concat([0, i]);
      }
      a.push(arr)
    }
    return a
  }, []);

}

var res = fillMonthHoles(data);
// loop over results and log each subarray for demo only
res.forEach(a => console.log(JSON.stringify(a)))
.as-console-wrapper {
  max-height: 100%!important;
}
<script>
  var data = [
    ["Ilhem", "Ben Salah", 4, 1],
    ["Ilhem", "Ben Salah", 3, 2],
    ["Ilhem", "Ben Salah", 3, 3],
    ["Ilhem", "Ben Salah", 3, 4],
    ["Sghaier", "Mahmoud", 1, 1]
  ]
</script>
n1bvdmb6

n1bvdmb62#

这很管用。

var  a = [      
  ["Ilhem", "Ben Salah", 4, 1],     
  ["Ilhem", "Ben Salah", 3, 2],
  ["Ilhem", "Ben Salah", 3, 3],
  ["Ilhem", "Ben Salah", 3, 4],
  ["Sghaier", "Mahmoud", 1, 1],
  ["Sghaier", "Mohammad", 15, 2],
];

var result = [];
while(a.length>0)
{
    var item = a[0], firstname = item[0], lastname = item[1];
    var matchedarr = a.filter(function(item){
            return (item[0] == firstname && item[1] == lastname);
        });
    for(var j=1;j<=12;j++)
    {
        var arr = matchedarr.filter(function(item){
            return item[3]==j;
        });
        arr = arr[0] || [item[0],item[1],0,j];
        result.push(arr);
    }
    a = a.filter(function(item){
        return item[0]!==firstname || item[1]!==lastname;
    });
}

console.log(result);

相关问题