ES6 Map Reduce 数组通过 Redux 状态的映射和填充变平

ES6 Map Reduce array flatten with mapping and padding from Redux state

我正在使用 ES6 编写一个 React/Redux 应用程序,我想要一种有效的方法来映射此数据:

[
  {total: 50, label: "C1"}, 
  {total: 120, label: "C2"}, 
  {total: 220, label: "C4"}
]

如下所示:

[
  {50, "Category 1"}, 
  {120, "Category 2"}, 
  {0, "Category 3"}, 
  {220, "Category 4"}
  {0, "Category 5"}, 
]

关键在于它会展平原始数组并重新标记标签值并填充缺失的键。

我可以用一些丑陋的 JS 迭代它来做到这一点,但我正在努力让它与一个简单而优雅的 reduce 箭头函数机制一起工作,我确信这是可能的。

使用.map().

var foo = [{
    total: 50,
    label: "C1"
  },
  {
    total: 120,
    label: "C2"
  },
  {
    total: 220,
    label: "C4"
  }
];

var flatFoo = foo.map((obj) => {
  return [
    obj.total,
    `${obj.label.substr(0, 1)}ategory ${obj.label.substr(1, 1)}`
  ];
});

console.log(flatFoo);

这里有一些选项...

const data = [
  {total: 50, label: "C1"}, 
  {total: 120, label: "C2"}, 
  {total: 220, label: "C4"}
];

const stripChars = s => (s || '').replace(/[a-z]/i, '');


function fillTo(limit, data) {

  return Array
    .from({length: limit}, (_, i) => (
      data.find(o => stripChars(o.label) == i) ||
      { total: 0, label: `C${i}` }
    ))
  ;
}


const toMap = data => data.reduce(
  (res, ) => Object.assign(res, {
    [.total]: `Category ${stripChars(.label)}`
  }), Object.create(null)
);

const pairwise = data => data.map(
   => [.total, `Category ${stripChars(.label)}`]
);

console.log('fillTo', fillTo(6, data));
console.log('toMap', toMap(data));
console.log('pairwise', pairwise(data));

/**
 * 1. fill the array
 * 2. chose your transformer 
 * 
 * const d = fillTo(6, data);
 * console.log(pairwise(d));
**/

使用 Array.prototype.reduce 创建一个 哈希表 以将缺失的键填充到 数组的数组 - 请参阅下面的演示:

var arr = [{total: 50, label: "C1"},{total: 120, label: "C2"},{total: 220, label: "C4"}];

// create a hash table first
var hash = arr.reduce(function(p,c){
  var key = c.label.replace(/[^\d]/g,'');
  p[key] = c;
  // largest key
  p['count'] = (+key > (p['count'] || 0)) ? +key : p['count'];
  return p;
}, Object.create(null));

// accumulate the result
var result = [];
for(var i = 0; i < hash['count']; i++) {
  var el = hash[i + 1] || {};
  result.push([el.total || 0, 'Category '+ (i+1)]);
}
console.log(result);
.as-console-wrapper {top: 0;max-height: 100%!important;}

您可以先对原始数组进行排序以获得最小值和最大值,然后使用循环添加缺失的元素。

var data = [
  {total: 220, label: "C14"},
  {total: 50, label: "C3"}, 
  {total: 120, label: "C10"}, 
  {total: 220, label: "C7"}
]


data.sort((a, b) => a.label.slice(1) - b.label.slice(1))
var result = [];

data.forEach(function(e, i) {
  var n = e.label.slice(1);
  var next = data[i + 1]
  result.push([e.total, 'Category ' + n]);

  if (next) {
    for (var j = n; j < +(next.label.slice(1) - 1); j++) {
      result.push([0, 'Category ' + (+j + 1)])
    }
  }
})

console.log(JSON.stringify(result, 0, 4))