Array reduce


sample 1

const ages = [21, 18, 42, 40, 64, 63, 34];
const maxAge = ages.reduce((max, age) => {
  console.log(`${age} > ${max} = ${age > max}`);
  if (age > max) {
    return age;
  } else {
    return max;
  }
}, 0);
console.log('maxAge', maxAge);


sample 2

const ages = [21, 18, 42, 40, 64, 63, 34];
// less syntax
const max = ages.reduce((max, value) => (value > max ? value : max), 0);
console.log('max', max);


sample 3

const colors = [
  {
    id: '-xekare',
    title: 'rad red',
    rating: 3,
  },
  {
    id: '-jbwsof',
    title: 'big blue',
    rating: 2,
  },
  {
    id: '-prigbj',
    title: 'grizzly grey',
    rating: 5,
  },
  {
    id: '-ryhbhsl',
    title: 'banana',
    rating: 1,
  },
];
const hashColors = colors.reduce((hash, { id, title, rating }) => {
  hash[id] = { title, rating };
  return hash;
}, {});
console.log(hashColors);


sample 4

const colors = ['red', 'red', 'green', 'blue', 'green'];
const distinctColors = colors.reduce(
  (distinct, color) =>
    distinct.indexOf(color) !== -1 ? distinct : [...distinct, color],
  []
);
console.log(distinctColors);


Links:

https://github.com/MoonHighway/learning-react/tree/master/chapter-03