数组内容的聚合

时间:2018-06-04 15:53:57

标签: javascript arrays

鉴于

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

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"

挑战

使用"最严重的"返回一个合并的单个数组。给定索引的对象 - 由其"类型"标识。给定顺序的属性(忽略空位):

  1. "NEUTRAL"
  2. "GREEN"
  3. "YELLOW"
  4. "RED"
  5. 输出的长度由列表中最长的输入数组决定。 对于上面给出的示例,需要以下输出:

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

    第一种方法

    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];
        }
    }));
    

    我无法感觉到这应该更加简单和短暂。

2 个答案:

答案 0 :(得分: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);
}, []);

答案 1 :(得分: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; }