Reducing nested array

array reduce
javascript flatten array of objects
reduce array to object
array reduce polyfill
arra reduce
sum array javascript
javascript map, reduce
javascript sum array of objects

I am receiving this JSON from my backend and i need to work out the count of "concrete_compressive_cylinder_100"'s where picked_up = false

concrete_samples (can be multiple per work order) can be null ( key is always present )

sample_specimens ( 1 per concrete_sample) can be null ( key is always present )

concrete_compressive_cylinder_100 ( null to 500 per sample_specimens )

{ 
   "uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
   "org_workorder_id":1000,
   "concrete_samples":[ 
      { 
         "uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
         "workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
         "org_sample_id":5001,
         "sample_specimens":{ 
            "concrete_compressive_cylinder_100":[ 
               { 
                  "uuid":"b9ef3a8a-2945-41e6-a34d-d90d1bd64819",
                  "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                  "picked_up":true
               },
               { 
                  "uuid":"d43f15b3-2208-43de-8fff-8d237c6918f9",
                  "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                  "picked_up":true
               },
               { 
                  "uuid":"472f832a-6f07-4af6-97ea-e6dc7b9b3799",
                  "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                  "picked_up":true
               }
            ],
            "concrete_compressive_cylinder_200":[ 
                { 
                   "uuid":"d659d058-e4ec-4f72-9d73-9ea98295715a",
                   "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                   "picked_up":true
                },
                { 
                   "uuid":"777372e0-3e58-4292-bae4-bec84dfe1402",
                   "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                   "picked_up":true
                },
                { 
                   "uuid":"f63f7102-7673-4e71-97e5-2d85e0c1a93d",
                   "sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b",
                   "picked_up":true
                }
             ]
         }
      },
      { 
         "uuid":"61138cf3-0c49-4495-8a89-533c0a6e50bc",
         "workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7",
         "org_sample_id":5002,
         "sample_specimens":{ 
            "concrete_compressive_cylinder_100":null,
            "concrete_compressive_cylinder_200":null
         }
      }
   ]
}

I've gotten this far but it dosen't really work and now im more confused some guidance would be great

        const out = res.data.concrete_samples.reduce((acc, sample) => {
          const { sample_specimens } = sample;
          const concrete_compressive_cylinder_100 = Object.keys(sample_specimens)["concrete_compressive_cylinder_100"];

            const specimens = concrete_compressive_cylinder_100.map(obj => {
                obj.picked_up ? console.log("picked up") : console.log("Not pickedn up")
            });

        }, []);

Array.prototype.reduce accepts a function whose return value is eventually returned from reduce itself. The function is passed each element of the array, along with the value accumulated so far. For example,

[1, 2, 3].reduce((accumulator, element) => accumulator + element)
// => 6

You can also provide an initial value, which will be passed to your function as accumulator on the first iteration.

At a basic level, to count how many occurrences of an object with a certain property with reduce, you could use something like this,

let array = [
  { foo: 4 },
  { foo: 6 },
  { bar: 8 },
]

array.reduce((count, element) => {
  if (element.foo !== undefined) {
    return count + 1
  } else {
    return count
  }
}, 0)
// => 2

Extending this to your code (with extraneous data elided), with a nested reduce to get the count of cylinders with the desired picked_up property,

const data = {
  "concrete_samples":[ 
    {
      "sample_specimens":{ 
        "concrete_compressive_cylinder_100":[ 
          {
            "picked_up":true
          },
          {
             "picked_up":true
          },
          {
             "picked_up":true
          }
        ],
        "concrete_compressive_cylinder_200":[ 
          {
             "picked_up":true
          },
          {
             "picked_up":true
          },
          {
             "picked_up":true
          }
        ]
      }
    },
    {
      "sample_specimens":{ 
        "concrete_compressive_cylinder_100":null,
        "concrete_compressive_cylinder_200":null
      }
    }
  ]
}

const result = data.concrete_samples.reduce((count, sample) => {
  const cylinders = sample.sample_specimens.concrete_compressive_cylinder_100
  if (cylinders == null) {
    return count
  }
  const samplePickedUpCount = cylinders.reduce((pickedUpCount, cylinder) => {
    if (cylinder.picked_up) {
      return pickedUpCount + 1
    } else {
      return pickedUpCount
    }
  }, 0)
  return count + samplePickedUpCount
}, 0)

console.log(result)

How to Transform Any Data Structure with Reduce, [1, 2, 7, 3].reduce((acc, value) => { if (acc < value) acc = value; return acc; }, -​Infinity); // => 7. It can flatten nested objects (from Array or Object to Array ):. JavaScript Nested array are used to reduce declare multiple arrays. Nested array are also said to be multi-dimensional array. We can achieve nested arrays by index braces and mustache braces (JSON) style.


If I understand correctly, you'd like to obtain a new concrete_samples array where the array values of nested sample_specimens objects are reduced to the number of items where picked_up is true - one approach to that would be as documented in the following snippet:

const data={"uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7","org_workorder_id":1000,"concrete_samples":[{"uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7","org_sample_id":5001,"sample_specimens":{"concrete_compressive_cylinder_100":[{"uuid":"b9ef3a8a-2945-41e6-a34d-d90d1bd64819","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true},{"uuid":"d43f15b3-2208-43de-8fff-8d237c6918f9","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true},{"uuid":"472f832a-6f07-4af6-97ea-e6dc7b9b3799","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true}],"concrete_compressive_cylinder_200":[{"uuid":"d659d058-e4ec-4f72-9d73-9ea98295715a","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true},{"uuid":"777372e0-3e58-4292-bae4-bec84dfe1402","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true},{"uuid":"f63f7102-7673-4e71-97e5-2d85e0c1a93d","sample_uuid":"776a8ccb-82fd-4a42-a6eb-8f286a4a9c0b","picked_up":true}]}},{"uuid":"61138cf3-0c49-4495-8a89-533c0a6e50bc","workorder_uuid":"4ad7bfe1-48d6-488c-bfaf-33f7189a41d7","org_sample_id":5002,"sample_specimens":{"concrete_compressive_cylinder_100":null,"concrete_compressive_cylinder_200":null}}]};

const concreteSamplesResult = data.concrete_samples.map(sample => {
  
  // Iterate each key/value entry of sample_specimens, and reduce to a new 
  // specimens object that contains counts of picked_up: true items in sub array
  const sample_specimens = Object
    .entries(sample.sample_specimens)
    .reduce((specimens, entry) => {
    
    // Calculate count of picked_up items for arr of this entry
    const [key, arr] = entry;
    const count = Array.isArray(arr) ? 
      arr.reduce((total, item) => (total + (item.picked_up ? 1 : 0)), 0) : 0;
    
    // Add count for entry key to newly reduced sample_specimen object
    return { ...specimens, [key] : count };
    
  },{})
  
  return { ...sample, sample_specimens };

});

console.log(concreteSamplesResult);

Array.prototype.flat(), By default, the clone function will not copy over nested objects. Instead These functions all take an array and reduce it down to a single number. But what if that​  // es5 data.reduce(function(prev, next) { return prev + next[1]; }) // es6 syntax data.reduce((prev, next) => prev + next[1]) However I only do need the second value from each (nested) array. Any hints or tipps for me? I'm trying to sum all values within the array. // Edit: Thanks for the answers. The problem was, that I missed the initialValue at the end.


Check null > loop > check null > loop and count isn't it?

function someFunc(json) {
  const { concrete_samples } = json;
  if (!concrete_samples) return;

  let numberOFAvailableCylinder100s = 0;
  const doSomethingWithCylinder = cylinder => {
    console.log(cylinder.uuid);
    numberOFAvailableCylinder100s += 1;
  }

  concrete_samples.forEach(concrete_sample => {
    const { sample_specimens } = concrete_sample;
    if (!sample_specimens) return;
    findAvailableCylinder100(sample_specimens, doSomethingWithCylinder);
  })

  console.log(`count: ${numberOFAvailableCylinder100s}`);
}

function findAvailableCylinder100(sample_specimens, callback) {
  const { concrete_compressive_cylinder_100 } = sample_specimens;
  if (!concrete_compressive_cylinder_100) return;
  concrete_compressive_cylinder_100.forEach(cylinder => {
    if (!cylinder.picked_up) callback(cylinder);
  });
}

someFunc(yourJSONObject);

Iterating Over and Reducing Data, Flattening an array of arrays with the Reduce Method In JavaScript​​. We can use reduce to flatten nested amounts into a single array. The reduce () method executes a reducer function (that you provide) on each element of the array, resulting in single output value. JavaScript Demo: Array.reduce () const array1 = [1, 2, 3, 4]; const reducer = (accumulator, currentValue) => accumulator + currentValue; // 1 + 2 + 3 + 4 console.log (array1.reduce (reducer)); // expected output: 10 // 5 + 1 + 2 + 3 + 4 console.log (array1.reduce (reducer, 5)); // expected output: 15.


A Guide To The Reduce Method In Javascript​, We can slightly improve this code by omitting an empty array [] as the second argument for reduce(). Then the first value of the nested will be  In Excel, an Array Formula allows you to do powerful calculations on one or more value sets. The result may fit in a single cell or it may be an array. An array is just a list or range of values, but an Array Formula is a special type of formula that must be entered by pressing Ctrl + Shift + Enter.


How to simplify your codebase with map(), reduce(), and filter() in , Various functions that can be used to reduce an array and clearing junk values in Array. Also describes flatten multiple nested array. 2-D numpy arrays. Turns out we can cast two nested lists into a 2-D array, with the same index conventions. For example, we can convert the following nested list into a 2-D array: V=np.array([[1, 0, 0],[0,1, 0],[0,0,1]]) Example 4: creating a 2-D array or array with two access


Clearing A Array And Reduce Array Elements, Flatten The Nested , flat method so we have to flatten this array ourselves. So we'll write a function to flatten any array no matter how deeply nested the arrays are: function  We can slightly improve this code by omitting an empty array [] as the second argument for reduce (). Then the first value of the nested will be used as the initial acc value. Thanks to Vladimir Efanov. let flat = nested.reduce((acc, it) => [acc,it]); // flat is [1, 2, 3, 4, 5, 6, 7, 8, 9]