0

I have an array of arrays, and when I iterate through them with foreach, I try to call flatmap on the items, but js says flatmap is not a function

var arrayItems = [];
arrayItems.push(["a", "b", "c", "d", "e"]);
arrayItems.push(["c", "d", "e", "f"]);
arrayItems.push(["c", "e", "f", "g", "h"]);
arrayItems.push(["e", "f", "g", "h"]);

var variations = generate_variations(arrayItems);

function generate_variations(arrayItems) {

  var variations = [];
  //https://stackoverflow.com/questions/43241174/javascript-generating-all-combinations-of-elements-in-a-single-array-in-pairs/43241287

  arrayItems.forEach(([key, value]) =>
    variations.push(value.flatMap(
      (v, i) => value.slice(i + 1).map(w => [v, w])
    )));

  return variations;
}

console.log(variations);

Here is a simple flatmap that works fine (I tried to place this in a for loop) from Javascript - Generating all combinations of elements in a single array (in pairs)

var array = ["apple", "banana", "lemon", "mango"];

var result = array.flatMap(
  (v, i) => array.slice(i + 1).map(w => [v, w])
);

console.log(result);
Barmar
  • 741,623
  • 53
  • 500
  • 612
giorgio79
  • 3,787
  • 9
  • 53
  • 85

1 Answers1

2

Change this line:

arrayItems.forEach(([key, value]) =>

To:

arrayItems.forEach((value) => 

var arrayItems = [];
arrayItems.push(["a", "b", "c", "d", "e"]);
arrayItems.push(["c", "d", "e", "f"]);
arrayItems.push(["c", "e", "f", "g", "h"]);
arrayItems.push(["e", "f", "g", "h"]);

var variations = generate_variations(arrayItems);


function generate_variations(arrayItems) {

  var variations = [];
  //https://stackoverflow.com/questions/43241174/javascript-generating-all-combinations-of-elements-in-a-single-array-in-pairs/43241287

  arrayItems.forEach((value) => 
    variations.push( value.flatMap(
      (v, i) => value.slice(i + 1).map(w => [v, w])
    )));
    
  return variations;
}

console.log(variations);
sbgib
  • 5,580
  • 3
  • 19
  • 26
  • Wow that works! Interesting, leaving away key makes it work. – giorgio79 Apr 17 '21 at 10:44
  • 2
    In the syntax of `forEach()`, the value is the [first argument in the callback function](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/forEach#syntax). – sbgib Apr 17 '21 at 10:46