Array manipulations using the reduce method
Wed Apr 17 2024
Sum of Elements in Array:
Implemented a straightforward function to sum all elements in an array, demonstrating reduce as an effective tool for aggregating numerical data.
Prefix Sum Array:
Developed a function to generate a prefix sum array, which provides cumulative sums up to each index, illustrating reduce's capability to build progressively complex arrays from simple lists.
Flatten a Nested Array:
Created a recursive flatten function that handles deeply nested arrays, showcasing how reduce can be adapted for tasks requiring depth handling and recursion.
Group Elements by Age:
Utilized reduce to group objects by a common key (age in this case), forming a hash map where each key points to an array of objects sharing that key, demonstrating its utility in structuring and categorizing data.
Count Occurrences of Elements:
Crafted a function to count the frequency of elements in an array, turning a list of items into a map of counts, which highlights reduce's ability to efficiently transform and summarize data.
1//Sum of Elements in Array
2const numbers = [1, 2, 3, 4, 5];
3
4function sum(arr) {
5  return arr.reduce((acc, item) => {
6    return (acc += item);
7  }, 0);
8}
9console.log(sum(numbers));
10
11//Prefix Sum Array
12let arr = [3, 1, 5, 2, 4];
13
14function prefixSumArray(arr) {
15  let prefArr = arr.reduce(
16    (acc, item) => {
17      return [...acc, acc[acc.length - 1] + item];
18    },
19    [0]
20  );
21  prefArr.shift();
22  return prefArr;
23}
24
25console.log(prefixSumArray(arr));
26
27//Flatten a nested Array
28const nested = [[2, 3], 1, 4, [5, [6, 7]]];
29
30function flatten(arr) {
31  return arr.reduce((acc, item) => {
32    if (Array.isArray(item)) {
33      if (item.length === 0) {
34        return acc;
35      } else {
36        return acc.concat(flatten(item));
37      }
38    } else {
39      acc.push(item);
40      return acc;
41    }
42  }, []);
43}
44
45console.log(flatten(nested));
46
47//Group Eleements by Age
48const people = [
49  {name: 'Alice', age: 25}, {name: 'Bob', age: 30}, {name: 'Charlie', age: 25}
50]; 
51// Output: 
52//{25: [{name: 'Alice', age: 25}, {name: 'Charlie', age: 25}], 30: [{name: 'Bob', age: 30}]}
53function groupByAge(arr){
54  return arr.reduce((acc, item)=>{
55    acc[item.age] = acc[item.age] || []; 
56    acc[item.age].push(item);
57    return acc;
58  },{})
59}
60
61console.log(groupByAge(people))
62
63//Count Occurrences of Elements
64const fruitOccur = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple']; 
65// Output: {apple: 3, banana: 2, orange: 1}
66
67
68function countOccurrences(arr) {
69  return arr.reduce((acc, item) => {
70    acc[item] = (acc[item] || 0) + 1;
71    return acc;
72  }, {});
73}
74
75console.log(countOccurrences(fruitOccur))