Javascript - Generating all combinations of elements in a single array (in pairs)

后端 未结 9 648
天命终不由人
天命终不由人 2020-11-28 11:14

I\'ve seen several similar questions about how to generate all possible combinations of elements in an array. But I\'m having a very hard time figuring out how to write an a

9条回答
  •  旧时难觅i
    2020-11-28 11:40

    Here are some functional programming solutions:

    Using EcmaScript2019's flatMap:

    var array = ["apple", "banana", "lemon", "mango"];
    
    var result = array.flatMap(
        (v, i) => array.slice(i+1).map( w => v + ' ' + w )
    );
    
    console.log(result);

    Before the introduction of flatMap (my answer in 2017), you would go for reduce or [].concat(...) in order to flatten the array:

    var array = ["apple", "banana", "lemon", "mango"];
    
    var result = array.reduce( (acc, v, i) =>
        acc.concat(array.slice(i+1).map( w => v + ' ' + w )),
    []);
    
    console.log(result);

    Or:

    var array = ["apple", "banana", "lemon", "mango"];
    
    var result = [].concat(...array.map( 
        (v, i) => array.slice(i+1).map( w => v + ' ' + w ))
    );
    
    console.log(result);

提交回复
热议问题