Is it possible to generate n choose k combinations in Javascript by utilizing Array.flatMap?

An example of 5 choose 2 using JavaScript:


var array = [0,1,2,3,4];
    
var result = array.flatMap(
    (v, i) => array.slice(i+1).map(w => [v, w]) 
);
    
console.log(result);

How could I apply this method to calculate 5 choose 3?

Answer №1

Take your code to the next level by adding another layer of nesting:

var array = [0,1,2,3,4];

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

console.log(result);

If you find this approach challenging, consider implementing it with recursion instead:

function choose(arr, k, prefix=[]) {
    if (k == 0) return [prefix];
    return arr.flatMap((v, i) =>
        choose(arr.slice(i+1), k-1, [...prefix, v])
    );
}

console.log(choose([0,1,2,3,4], 3));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

I am having an issue where my div element is not inheriting the width of its

I am encountering an issue where I have one div and I check the width of that div in jQuery. I then try to set the same width on the next div, but the width does not appear. Can someone please assist me with this? Here is my code: $(document).ready(funct ...

Testing the performance of MEAN applications under heavy load

As I work on developing an application using the cutting-edge MEAN stack, I have successfully deployed the initial version to a server. This application comprises of a static HTML file (along with CSS and some images) as well as numerous JavaScript files. ...

What is the most efficient way to retrieve a value (specifically an access token) within a function without using

const callback = (req, res) => { // Your application requests refresh and access tokens after verifying the state parameter if (state === null || state !== storedState) { ... } else { res.clearCookie(stateKey); var authOptions = {...} ...

Arrange the elements of the array in MongoDB based on the last element

Seeking a way to sort documents based on the last interaction, utilizing an array called meta_data.access_times. This array updates every time a user interacts, with a new date object being added to its last element. Is there a method to sort by the last e ...

Exploring AngularJS ng-repeat features for custom attribute settings

I'm currently facing a challenge in removing multiple repetitive divs by utilizing ng-repeat. <!-- I have 21 of these --> <div class="table-row"> <span class="glyphicon glyphicon-wrench"></span> <label>Chlo ...

Creating a Spotify-inspired overlay scrollbar on a website using a combination of CSS and Javascript techniques

UPDATES (4th March, 2024): I have revised my question to eliminate unnecessary code and wording. It should now be clearer and more readable. I've learned that Spotify's scrollbar was created using javascript I'm looking to create a scrollb ...

Tips for duplicating specific div elements

Is there a way to create copies of selected divs within the same panel using a Javascript report designer? I attempted to achieve this by using the following code snippet: function DesignerClone() { $(".ui-selected").each(function () { va ...

retrieve PHP function calls as an array using Ajax

While working in PHP, I have encountered a situation where I needed to call a PHP function using AJAX: <button onclick="loop()">Do It</button> function loop() { $.get("ajax.php", { action: "true" }, function(result) { $("in ...

The file type input is not directing to the correct folder in Internet Explorer version 9

Could someone please assist me with this problem in IE9? After I select a file to upload, then choose another one, it shows "fakepath" in IE9. See the image below for more information: https://i.sstatic.net/QsJFk.png https://i.sstatic.net/3nWRC.png htt ...

Obtain vine thumbnails using Angular

In an attempt to retrieve a vine thumbnail as outlined in their documentation, I wrote the following code: <!-- language: lang-js --> var onGetVineThumbnailSuccess = function( videoUrl ) { return function( response ) { var args = { videoUrl: ...

Creating a Union Type from a JavaScript Map in Typescript

I am struggling to create a union type based on the keys of a Map. Below is a simple example illustrating what I am attempting to achieve: const myMap = new Map ([ ['one', <IconOne/>], ['two', <IconTwo/>], ['three ...

Issue with Angular custom directive failing to set value even after promise resolution

I created a custom directive that works well when the user enters a value. However, I'm facing an issue where the input field is not being rendered when the form is loaded. Below is my directive code: var cuitModule = angular.module('cuitModu ...

Error message: Attempting to access index 0 of an undefined property within a Vue.js v-for loop

The return of console.log(this.sights) is an array containing 20 objects, each with properties such as name, photos, references, etc. My current goal is to iterate through these objects, displaying their names and photo_references. Here is how I am attempt ...

Reorganize HTML table rows based on the last row within a rowspan

I would like to organize the data in the table below according to the values in the last row of a rowspan. https://i.sstatic.net/R9OBF.png Looking at the image, I am aiming to sort the table based on the "Cumulative hours" value. Here, I have implemented ...

The input field does not contain the chosen date

Utilizing the react-dates library from Airbnb for date selection has been a bit challenging in conjunction with redux form. Upon clicking the select date button, the calendar interface appears. However, upon choosing a date, the input box remains empty ins ...

The tabs in bootstrap appear to be functioning properly, but the data is not displaying as expected

Currently, I am incorporating Bootstrap into my project and I am attempting to include a Twitter Bootstrap tab. I have already added jQuery and bootstrap-tabs.js to my project. Below is the script that I have added: <script> $('#myTab a&apos ...

Obtain the month, day, or year from a timestamp

Can anyone provide guidance on extracting a specific date format (date, month, day, year) from a timestamp? I am interested in implementing this feature within a view using Backbone JS. ...

Having trouble with VueJS method not getting called after an asynchronous function callback?

I'm currently utilizing VueJS along with Stripe to create a form that can be submitted without needing to refresh the page. While the Stripe functionality is operational, the issue I'm facing doesn't seem to be directly related to Stripe. T ...

Having trouble getting ImageBackground resizeMode to function within the style props?

I have recently started developing a simple app in react native and I am facing an issue with the resizeMode property of ImageBackground. It seems that the resizeMode is not working when used within the stylesheet, however, it works fine when directly adde ...

Is it possible to identify iOS Safari exclusively without including iOS Chrome, Firefox, and other browsers in the filter?

For those familiar with working on iOS web applications, it's known that Apple's policy causes Chrome and other mobile browsers on iOS to use an outdated javascript engine. Because of this, we need to disable certain rendering for Chrome and othe ...