JavaScript code to find all possible subarrays of an array containing n elements

I've been working on creating a function that can generate subsets from an array based on a specified number of elements, but I haven't quite cracked it yet.

I came across a function that was supposed to do the job, but it turned out to be too complex and didn't quite meet my requirements. It was attempting to create subsets with three elements from a four-element array, but it wasn't even taking the number of elements (n) as a parameter. Additionally, it was generating duplicate subsets, so I needed to figure out how to filter those out.

function findSubsets(array) { 
    var answers = []; 
    var firstArray = array; 
    for (i = 0; i < array.length; i++) { 
       array = firstArray; 
       for (var k = 0; k < array.length; k++) { 
          if (k != i) { 
              var subset = array.splice(k, 1); 
              answers.push(array); array.splice(k, 0, subset[0]);
          } 
       }
    } 
}

Answer №1

This method offers a simplified approach. It is designed to avoid generating unnecessary temporary arrays, making it more efficient than it may initially appear.

function generateGroups(arr, num) { 
    var results = []; 
    for(var i = 0; i < arr.length; i += num) {
        results.push(arr.slice(i, i + num));
    }
    return results;
}

generateGroups([1, 2, 3, 4, 5, 6, 7, 8, 9], 2) // --> [[1, 2], [3, 4], [5, 6], [7, 8], [9]]
generateGroups([1, 2, 3, 4, 5, 6, 7, 8, 9], 3) // --> [[1, 2, 3], [4, 5, 6], [7, 8, 9]]

Answer №2

Check out this handy solution:

var subArray = (function() {
  return {
    findResult: findResult
  }

  function findResult(array, num) {

    function isMatch(value) {
      return value.length === num;
    }

    var ps = [
      []
    ];
    for (var i = 0; i < array.length; i++) {
      for (var j = 0, len = ps.length; j < len; j++) {
        ps.push(ps[j].concat(array[i]));
      }
    }
    return ps.filter(isMatch);
  }
})();

var numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9]; console.log(subArray.findResult(numbers, 2));

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

If a dynamic route does not exist in NextJS, display a 404 error. Otherwise, show a loading spinner

I am facing an issue with the dynamic routes in my NextJS app, specifically /team/[id]. When the page loads, it queries the API to retrieve information based on the team ID. If the ID does not exist in the API, a 404 error is returned. However, I am strugg ...

Encountering issues with Jquery while retrieving data from a .json URL

While attempting to retrieve data using a small script that usually works with URLs producing JSON data, I encountered a syntax error when trying it with a URL ending in .json. //error Uncaught SyntaxError: Unexpected token : http://frontier.ffxiv.com/wo ...

When the dependency value transitions from 1 to 0, useEffect fails to trigger

I'm really puzzled by how useEffect behaves in this scenario: Check out this code snippet: const numVertices = selectionProvider.verticesSelectionProvider.count; console.log('RENDER ---> COUNT = ', numVertices); useEffect(() => { ...

Steps to bring an image forward on a canvas to enable its onclick function

One of the challenges I'm facing involves an image of a pawn on a board. The image is set up with an onclick function that should trigger an alert when clicked. However, there is a canvas positioned above the image, which is interfering with the funct ...

Interfaces and Accessor Methods

Here is my code snippet: interface ICar { brand():string; brand(brand:string):void; } class Car implements ICar { private _brand: string; get brand():string { return this._brand; } set brand(brand:string) { this. ...

Submit data in the manner of a curl request

Instead of using a curl command to push a file to a web server, I am attempting to create a simple webpage where I can select the file and submit it. Here is the HTML and JavaScript code I have written for this purpose: <html> <body> <i ...

Dynamically add index to attribute as it updates

Having an issue with my dynamic button element: <button v-on:click="changeRecord(element)" v-b-modal.modal-5>Aendern</button> This button is generated dynamically within a v-for loop. Instead of manually including the attribute name like v-b- ...

Tips for combining a new element using hooks in React JS?

Here is the structure I am working with: https://i.sstatic.net/bF7Wb.png My goal is to update the metrics by adding new data: const [data, setData] = useState<any>({}); getServerResourceUsage(serverId, intervalTime) .then(res => { ...

Modify a unique custom binding handler in such a way that it is designated using an Immediately Invoked Function Expression

I am currently working on improving a custom binding handler by converting it into an Immediately Invoked Function Expression (IIFE). Despite researching IIFE online, I am still unsure of how to make the necessary changes to my custom handler. Can someon ...

Invoking functions with JavaScript objects

Can anyone help me figure out what is wrong with the following JavaScript code? <form> What is 5 + 5?: <input type ="number" id ="num_answer;"/> </form> <script> function basic_math(){ var num_val = document.getElem ...

Generating .npy data with Numpy to use as input for a Convolutional Neural Network

I am a beginner in Python and working with a .npy file as input for my CNN model. Many tutorials I have found use Keras, but unfortunately I am not permitted to use it. Therefore, I need to know how to read just one array from my .npy file. The file contai ...

What is the best way to deselect all "md-checkboxes" (not actual checkboxes) on an HTML page using a Greasemonkey script?

After spending a frustrating amount of time trying to disable the annoying "md-checkboxes" on a certain food store website, despite unchecking them multiple times and reporting the issue without any luck, I have come to seek assistance from knowledgeable e ...

Guide to turning off the Facebook iframe page plugin

I am facing a challenge with embedding a facebook iframe on my website. I want to disable it once the screen width reaches a specific point, but I am struggling to make the iframe disappear properly. Here is how I have attempted to implement this: window.o ...

Load CKEditor.js with RequireJS following the textarea element

If you need a WYSIWYG editor, CKEditor could be the answer. Check out their documentation here. To properly load CKEditor, make sure to add the following script tag in the header: <script src="../ckeditor/ckeditor.js"></script> ... Then, inc ...

The communication between a Firefox XUL extension and a webpage

Currently developing a Firefox XUL extension and in need of incorporating interaction between the web page and the extension. For instance, whenever a link is clicked on the page, I would like to trigger a function within the XUL extension. Is there any k ...

Is there a way to access the userID in the React.js front-end?

As I work on completing my Full Stack Web app with JWT token authentication based on roles, I find myself facing challenges with the front-end development. Specifically, I am unsure of the best practice for retrieving the UserID in the front-end to facil ...

Looking for a way to incorporate an image source property into a larger image?

I am working on a function that will enlarge an image when clicked on from a selection of 5 or more available images. The idea is that clicking on a small image will trigger the display of a larger version of that image in a frame. Here is an example of t ...

What is the best method to access an element with Vue.js?

I currently have a form set up like this <form v-on:submit.prevent="save_data(this)"></form> and a method defined in Vue.js like this methods: { save_data: function(f){ } } In jQuery, we can access the form using $(f)[0] My question ...

Maintain the functionality of an object even when it is created using the "bind" method

I'm working with a function that has the following structure: var tempFun = function() { return 'something'; } tempFun.priority = 100; My goal is to store this function in an array and bind another object to it simultaneously, like so ...

Troubleshooting focus loss in React input fields within a Datatable component implemented in a

I noticed an issue with my Datatable where the input field loses focus whenever I type a character and define the component inside another component. Surprisingly, when I directly place the component in the datatable, it works perfectly fine. I understand ...