JS reduce-仅求和对象中的数组长度

时间:2019-06-28 09:50:12

标签: javascript arrays object ecmascript-6 reduce

我具有以下数据结构:

const arr = [    
    {key: 0, x: [], y: []},
    {key: 0, x: [], y: []}
]

我想检查所有数组是否为空,我如何使用reduce做到这一点?到目前为止,我的代码:

arr.reduce((count, acc) => {
    return acc !== 'key' ? count + acc.length : count
}, 0)

6 个答案:

答案 0 :(得分:3)

您可以将key从对象中取出,并检查所有长度是否为零。

const
    array = [{ key: 0, x: [], y: [] }, { key: 0, x: [], y: [] }],
    allZero = array.every(({ key, ...o }) =>
        Object.values(o).every(({ length }) => !length));

console.log(allZero);

总结

const
    array = [{ key: 0, x: [], y: [] }, { key: 0, x: [], y: [] }],
    sum = array.reduce((s, { key, ...o }) =>
        Object.values(o).reduce((t, { length }) => t + length, s), 0);

console.log(sum);

答案 1 :(得分:1)

reduce有点笨拙,而且您正在遍历数组中的项,而不是您所期望的键。

改为使用Array.every

const arr = [    
    {key: 0, x: [], y: []},
    {key: 0, x: [], y: []}
]

const arr2 = [    
    {key: 0, x: [1,2,3], y: []},
    {key: 0, x: [], y: []}
]

function areAllEmpty(a){
    return a.every(i => i.x.length == 0 && i.y.length == 0); 
}

console.log(areAllEmpty(arr));
console.log(areAllEmpty(arr2));

答案 2 :(得分:1)

由于acc将是数组中的对象,因此应检查对象属性即数组。为此,请使用Object.values,并对每个对象中的数组使用另一个reduce,并排除key

const arr = [    
    {key: 0, x: [], y: []},
    {key: 0, x: [], y: []}
];

const res = arr.reduce((a, { key, ...c }) => a + Object.values(c).reduce((e, { length: f }) => e + f, 0), 0);
console.log(res);

答案 3 :(得分:0)

您可以在filter()上使用Object.values来仅获取数组值。然后flat(),然后将长度添加到结果中

const arr = [    
    {key: 0, x: [], y: []},
    {key: 0, x: [], y: []}
]

let res = arr.reduce((count, acc) => {
    return count + Object.values(acc).filter(x => x.constructor === Array).flat().length
}, 0)

console.log(res)

答案 4 :(得分:0)

使用Array.reduce()对对象中的仅数组长度求和:

const arr = [    
    {key: 0, x: [], y: [], abc: "hsgg" },
    {key: 0, x: [1, 2, 3, 4], y: [1, 2]}
];

const c = arr.reduce((count, obj) => {
    Object.values(obj).forEach(v => {
      if(Array.isArray(v)) count += v.length;
    });
    return count;
}, 0);

console.log(c);

请注意,在其他答案中,字符串的长度也计算在内

答案 5 :(得分:0)

Array.every是更好的选择。您可以遍历对象的所有值并测试它们是否为数组,如果为数组,则返回false(如果它们不为空)。 every将在找到一个非空数组后立即停止 ,或结束迭代的结束,以先到者为准。

const arr = [    
  {key: 0, x: [], y: []},
  {key: 0, x: [], y: []}
];

const arr2 = [    
  {key: 0, x: [], y: [1]},
  {key: 0, x: [], y: []}
];

const allEmpty = (arr) => arr.every(el => {
  for (let v of Object.values(el)) {
    if (Array.isArray(v) && v.length > 0) return false;
  }
  return true;
});

console.log(allEmpty(arr));
console.log(allEmpty(arr2));

相关问题