0

The function must project each element of the specified array to a sequence and flatten the resulting sequences into one array.

I have the function that must return the flattened array based on the given selector function (childrenSelector) but facing issues when applying slice() function.

When applying slice as a selector function, it says

TypeError: x.slice is not a function

function flattenArray(arr, childrenSelector) {
  return arr.reduce((accumArr, currVal) => {
      console.log(currVal);
      return Array.isArray(currVal) 
        ? accumArr.concat(currVal.map(childrenSelector)) 
        : accumArr.concat(childrenSelector(currVal))
    }, []
  );
}

flattenArray([[11, 12, 13, 14, 15], [21, 22, ,23, 24, 25], [31, 32, 34, 35]], x => x.slice(0, 2))

Is there any solution for this issue?

2
  • 2
    What's the desired output? Commented Jul 30, 2019 at 7:57
  • So, it should do the slices for each child array first, then it should combine those all into one flat array? Commented Jul 30, 2019 at 8:00

1 Answer 1

3

The problem is that, when iterating over the outer array, the conditional

Array.isArray(currVal)

is fulfilled, so

accumArr.concat(currVal.map(childrenSelector))

runs when currVal is an array of numbers. But numbers don't have a .slice method.

Instead, call childrenSelector on the currVal, without .map (so that the array is sliced):

function flattenArray(arr, childrenSelector) {
  return arr.reduce((accumArr, currVal) => {
    return accumArr.concat(childrenSelector(currVal));
  }, []);
}

console.log(
  flattenArray([
    [11, 12, 13, 14, 15],
    [21, 22, , 23, 24, 25],
    [31, 32, 34, 35]
  ], x => x.slice(0, 2))
);

You can also use flatMap:

const flattenArray = (arr, childrenSelector) => arr.flatMap(childrenSelector);

console.log(
  flattenArray([
    [11, 12, 13, 14, 15],
    [21, 22, , 23, 24, 25],
    [31, 32, 34, 35]
  ], x => x.slice(0, 2))
);

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.