0

I am using reduce function and some reason I get an error on the console:

(index):77 Uncaught TypeError: filtered.push is not a function

DispatchedNumber should exist before mapping into Lines array.

function payload(order) {
  return {
    OrderId: order.ORDERID,
    Lines: order.ITEMS.reduce(function(filtered, item) {
      if (item.DispatchedNumber != undefined) {
        var newItem = {
          Qty: item.Qty,
          QtyShipped: item.DispatchedNumber
        }

        filtered.push(newItem);
      }

      return filtered;
    })
  }
}

test = payload({
  "ORDERID": 1233,
  "ITEMS": [
    { Qty: 123, DispatchedNumber: 111 },
    { Qty: 111 },
    { Qty: 444, DispatchedNumber: 555 },
    { Qty: 443, DispatchedNumber: 323 }
  ]
})

Usage:

console.log(JSON.stringify(test, null, 2));

Example: https://jsfiddle.net/j6097w9d/2/

user88432
  • 397
  • 1
  • 4
  • 13

2 Answers2

2

There was no initial value specified for the accumulator in the reduce function.

Please update to following

order.ITEMS.reduce(function(filtered, item) {
      if (item.DispatchedNumber != undefined) {
        var newItem = {
          Qty: item.Qty,
          QtyShipped: item.DispatchedNumber
        }

        filtered.push(newItem);
      }

      return filtered;
    }, []) // add the empty array (initial value of accumulator)

For reference, Array.reduce

Nikhil Aggarwal
  • 28,197
  • 4
  • 43
  • 59
0

Reduce Syntax

arr.reduce(callback[, initialValue])

You need to be initialise your filtered variable into reduce() function.

DEMO

function payload(order) {
  return {
    OrderId: order.ORDERID,
    Lines: order.ITEMS.reduce(function(filtered, item) {
      if (item.DispatchedNumber != undefined) {
        var newItem = {
          Qty: item.Qty,
          QtyShipped: item.DispatchedNumber
        }
        
        filtered.push(newItem);
      }
      
      return filtered;
    },[])
  }
}

var test = payload({
  "ORDERID": 1233,
  "ITEMS": [{ Qty: 123, DispatchedNumber: 111 },{ Qty: 111 },{ Qty: 444, DispatchedNumber: 555 },{ Qty: 443, DispatchedNumber: 323 }]
})


console.log(JSON.stringify(test, null, 2));
.as-console-wrapper {  max-height: 100% !important;  top: 0;}
Narendra Jadhav
  • 10,052
  • 15
  • 33
  • 44