我有一个对象数组:
let fileArray = [
{ filename: 'File1.txt', bytes: 12345, created: 1548360783511.728 },
{ filename: 'File2.txt', bytes: 34567, created: 1548361491237.182 },
{ filename: 'File3.txt', bytes: 23456, created: 1548361875763.893 },
{ filename: 'File4.txt', bytes: 56789, created: 1548360658932.682 }
];
我要对该数组进行的两件事是查找此数组sum of numbers中的所有文件的总字节,以及首先创建(最小)Obtain smallest value from array in Javascript?创建的文件。
我正在查看array.reduce(),但这似乎只适用于平面数组。它可以在对象数组的特定键上工作吗?还是我必须在当前数组中为该键的所有值创建一个新的临时数组,然后对这些值运行array.reduce()?
答案 0 :(得分:0)
老套路吗?
var totalBytes = 0;
for(let i = 0; i < fileArray.length; i++){
totalBytes += fileArray[i].bytes;
}
console.log(totalBytes);
和
var firstFileIndex = 0;
for(let i = 0; i < fileArray.length; i++){
if(fileArray[i].created < fileArray[firstFileIndex].created){
firstFileIndex = i;
}
}
console.log(fileArray[firstFileIndex].filename);
答案 1 :(得分:0)
这里有一个示例,说明如何使用reduce()执行此操作。首先,我们创建两种方法来减少数组,一种方法用于获取bytes
的总和,另一种方法用于获取最小的created
。最后,我们将reduce传递作为参数称为相关的reduce方法。
let fileArray = [
{filename: 'File1.txt', bytes: 12345, created: 1548360783511.728},
{filename: 'File2.txt', bytes: 34567, created: 1548361491237.182},
{filename: 'File3.txt', bytes: 23456, created: 1548361875763.893},
{filename: 'File4.txt', bytes: 56789, created: 1548360658932.682}
];
// Define reduce method for get the sum of bytes.
const reduceWithSumBytes = (res, {bytes}) => res += bytes;
// Define reduce method for get the minimum created.
const reduceWithMinCreated = (res, {created}) =>
{
return res && (created < res ? created : res) || created;
};
// Use reduce() with the previous methods.
console.log(fileArray.reduce(reduceWithSumBytes, 0));
console.log(fileArray.reduce(reduceWithMinCreated, null));