iAmLearning
iAmLearning

Reputation: 1174

Iterating an array of items in nodejs

I have an index.js from which I am calling util.js as below :

util.js

module.exports.getResult = json => {
  return json.hits.hits.map(element => {
    const { _source } = element;

    return _source.details
      .filter(item => item.hasOwnProperty('deliveryDetails'))
      .map(item => {
        return item.deliveryDetails
          .filter(deliveryDetail => deliveryDetail.noOfItems > 0)
          .map(deliveryDetail => {
            return {
              id: item.Id,
              name: _source.name,
              noOfItems: deliveryDetail.noOfItems,
            };
          });
      });
  });
};

Since I am returning multiple times the result from innermost .map is changed into an array of array. Is this what is expected when iterating or I am doing it wrong?

Then to get the result in one final array I have to do below in index.js:

const temp = helper.getResult(json);
const result = [].concat.apply([], [].concat.apply([], temp));

Is there any better way to do this?

Upvotes: 0

Views: 83

Answers (2)

Jack Bashford
Jack Bashford

Reputation: 44115

Yep - use flat. To get the depth, you just work out the length + 2.

const result = temp.flat(temp.length + 2);

Use a recursive function for reduce.

const flattenDeep = arr => arr.reduce((a, c) => a.concat(Array.isArray(c) ? flattenDeep(c) : c), []);
const result = flattenDeep(temp);

Upvotes: 1

RAJENDIRAN
RAJENDIRAN

Reputation: 27

Array.prototype.flattenDeep = function() {
   return this.reduce((acc, val) => Array.isArray(val) ? acc.concat(val.flattenDeep()) : acc.concat(val), []);
}


const result =  temp.flattenDeep();

Upvotes: 0

Related Questions