数组内容的聚合

问题描述 投票:-2回答:2

Given

一组数组(具有不同长度)的对象

const statusLists = [
    [
        { "type": "NEUTRAL" },
        { "type": "GREEN" }
    ],
    [
        { "type": "YELLOW" },
        { "type": "GREEN" },
        { "type": "GREEN" },
        { "type": "NEUTRAL" }
    ],
    [
        { "type": "GREEN" },
        { "type": "RED" },
        { "type": "NEUTRAL" },
        { "type": "GREEN" }
    ]
];

每个对象包含具有非数字属性的特定字段,例如, "NEUTRAL""GREEN""YELLOW""RED"

Challenge

返回一个统一的单个数组,其中包含给定索引的“最严重”对象 - 由给定顺序的“type”属性标识(忽略空位):

  1. "NEUTRAL"
  2. "GREEN"
  3. "YELLOW"
  4. "RED"

输出的长度由列表中最长的输入数组决定。对于上面给出的示例,预期以下输出:

[
    { "type": "YELLOW" },
    { "type": "RED" },
    { "type": "GREEN" },
    { "type": "GREEN" }
]

First Approach

const worstPerIndex = [];
statusLists.forEach(singleList => singleList.forEach((entry, i) => {
    const currentEntryType = entry[i].type;
    const worstPaymentStatusForPeriod = worstPerIndex[i] ? worstPerIndex[i].type : null;
    switch (worstPaymentStatusForPeriod) {
        case 'GREEN':
            if (currentEntryType === 'YELLOW' || currentEntryType === 'RED') {
                worstPerIndex[i] = entry[i];
            }
            break;
        case 'YELLOW':
            if (currentEntryType === 'RED') {
                worstPerIndex[i] = entry[i];
            }
            break;
        case 'RED':
            break;
        default:
            worstPerIndex[i] = entry[i];
    }
}));

我不能动摇这种感觉应该更加简单和简单。

javascript arrays
2个回答
2
投票

使用reduce可能非常简单:

const severity = s => ["NEUTRAL", "GREEN", "YELLOW", "RED"].indexOf(s);

 const result = statusLists.reduce((prev, curr) => {
   // Make sure that we take the longer one
   if(prev.length > curr.length) [prev, curr] = [curr, prev];
   // Join the previous and the current severities and take the more serious ones
   return curr.map((el, i) => severity(prev[i] && prev[i].type) > severity(el.type) ? prev[i] : el);
}, []);

0
投票

您可以获取最大索引并减少数组。

var statusLists = [[{ type: "NEUTRAL" }, { type: "GREEN" }], [{ type: "YELLOW" }, { type: "GREEN" }, { type: "GREEN" }, { type: "NEUTRAL" }], [{ type: "GREEN" }, { type: "RED" }, { type: "NEUTRAL" }, { type: "GREEN" }]],
    types = ["NEUTRAL", "GREEN", "YELLOW", "RED"],
    typeIndices = Object.assign(...types.map((t, i) => ({ [t]: i }))),
    result = statusLists.reduce((r, a) => {
        a.forEach(({ type }, i) => r[i] = types[Math.max(typeIndices[r[i]] || 0, typeIndices[type])]);
        return r;
    }, [])

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
© www.soinside.com 2019 - 2024. All rights reserved.