-1

I have an array of objects:

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

The two things I am wanting to do with this array is to find the total bytes of all files in this array sum of numbers and the File created first (smallest) Obtain smallest value from array in Javascript?.

I was looking at array.reduce(), but that only appears to work on a flat array. Can it work on specific keys of an array of objects or will I have to create a new temp array all values for that key in the current array and run array.reduce() on those values?

shaun
  • 1,223
  • 1
  • 19
  • 44
  • `reduce` works on *any* array. The only thing that changes is what the "current value" argument is. In your case, it would refer to an object. If `cur` was the current object, then `cur.bytes` would be the bytes. Your reduce would simply add `cur.bytes` to your accumulator. – Tyler Roper Jan 24 '19 at 20:44
  • 2
    That **is** a flat array. – zero298 Jan 24 '19 at 20:44

2 Answers2

0

The old fahsioned way?

var totalBytes = 0;
for(let i = 0; i < fileArray.length; i++){
    totalBytes += fileArray[i].bytes;
}
console.log(totalBytes);

and

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);
user3425506
  • 1,285
  • 1
  • 16
  • 26
0

Here you have an example of how to do this with reduce(). First we create the two methods that will reduce the array, one for get the sum of bytes, and another for get the minimum created. Finally, we call reduce passing as argument the related reduce method.

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));
Shidersz
  • 16,846
  • 2
  • 23
  • 48