Generate all conceivable combinations of elements found in the array

Looking to generate all possible combinations of elements (without repetition) from a given array and length.

For example, with an array of:

arr = ['a','b','c','d']

and a length of 3, the desired output would be a 2-dimensional array like this:

result = [
    ['a','b','c'],
    ['b','c','a'],
    ['c','a','b'],
    . . . etc.
]

This task has proven quite challenging for me so far.

Answer №1

The code snippet below employs a straightforward method, generating permutations and combinations of the specified length. To prevent duplicates in the output, the permutations are compared against a dictionary.

function createPermutations(inputData, length) {
  var currentSet = new Array(length), usedElements = new Array(length),
      seenPerms = {}, finalResult = [];
  
  function permute(index) {
    if (index == length) {
      if (!seenPerms[currentSet]) {
        seenPerms[currentSet] = true;
        finalResult.push(currentSet.slice());
      }
      return;
    }
    
    for (var j = 0; j < inputData.length; ++j) {
      if (!usedElements[j]) {
        usedElements[j] = true;
        currentSet[index] = inputData[j];
        permute(index + 1);
        usedElements[j] = false;
      }
    }
  }
  
  permute(0);
  return finalResult;
}

var resultPermutations = createPermutations(['a', 'a', 'b', 'b'], 3);
for (var k = 0; k < resultPermutations.length; ++k) {
  document.write('[' + resultPermutations[k].join(', ') + ']<br />');
}

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

Utilizing WebView and Javascript for Push Notifications

Is it feasible to utilize javascript on an external page within a WebView application to trigger push notifications? (For instance, if I have a function located at example.com/news, would it be possible to send a push notification from there?) Appreciate ...

Unlock the ability to retrieve the current Ember route directly within a component

I have a unique custom Ember component embedded within a controller. Currently, I am attempting to dynamically retrieve the name of the current route. In order to access the controller, I use: this.get('parentView') However, I am facing diffi ...

What is the best way to update my TypeScript array with new values in real-time?

Looking to dynamically populate my pieChartColors array so that it resembles the following structure: public pieChartColors:Array<Color> = [ { backgroundColor: '#141C48' }, { backgroundColor: '#FF0000' }, { backgroundColor: ...

Why does `npm init react-app` automatically select yarn as the default package manager? (npm version 6.14.5)

After executing the command npm init react-app, I noticed that npm automatically selects yarn as the default package manager for the newly created app. To resolve this, I followed the steps provided in How Do I Uninstall Yarn to remove yarn from my system. ...

Setting up jade includes with gulp-jade: A comprehensive guide

Struggling with setting up Jade includes in your gulpfile.js while using gulp-jade? Check out this link for more information. Below is a snippet from the gulpfile.js: var gulp = require('gulp'); var browserSync = require('browser-s ...

Exploring Illumination with Three.js

I'm interested in exploring the light properties further. I am curious about the variables used in the DirectionalLight.js and SpotLight.js source codes. Could you explain the difference between castShadow and onlyShadow? Is there a way to manage th ...

reduce the size of the image as the browser width decreases

Struggling with a webpage layout that features an image on the left and content area on the right, both with fixed widths. When reducing browser width, the image should not shrink but be cropped from the left side instead. Any solutions for this issue? ...

Refreshing an iframe located on disparate domains

There is a webpage called "main.jsp" within the domain "domain1". This page contains an iframe that loads content from another domain known as "domain2". Essentially, "main.jsp" serves as a common content platform, with the iframe displaying content from v ...

Nuxt's axios is encountering difficulties in managing the server's response

Having just started working with Nuxt.js, I encountered an unusual issue. There is an endpoint in my backend API that allows users to reset their password by sending a token along with a new password. Although the request is being sent correctly and the s ...

Tips for automating file uploads in HTML

I am having trouble filling the <input type="file"> element programmatically when trying to upload a file using a form. Can someone please provide me with guidance on how to accomplish this task? The method does not matter, I just want to achieve m ...

Getting the width of an element using a React ref is a helpful technique that allows you

I am struggling to retrieve the width of a select field using React Ref. https://i.sstatic.net/JJmqF.png this.selectRef.current is returning an object, but I can't seem to find a way to access the width of the element. <Select ful ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Adjusting the size of an HTML5 canvas using a class function when a resize event occurs

I'm attempting to adjust the size of a canvas element using a resizeCanvas() method triggered by a resize event. When I directly call the method, the canvas resizes without any issues. However, when the event handler triggers subsequent calls, I encou ...

What methods can I employ JSON to create a dynamic Sidebar within Nextjs?

[ { "type": "root", "children": [ { "type": "file", "route": "Open-EdTech/AWS-Associate-Notes/EC2.md", "title": "EC2", ...

What is the process for updating the internal TypeScript version in VS Code?

When using VS Code, I noticed it comes with its own TypeScript version: Is there a way to update this? The current version is 4.9.3. https://i.sstatic.net/vEx85.png ...

The Arrival of Link: A Countdown Timer

I'm attempting to create a countdown timer that reveals a link after 20 minutes. Currently, this is my progress... <script type="text/javascript"> window.onload = function() { countDown('my_div1', '<a href="cdtl.html" ...

`CSS Content Placeholder Issue When Used Alongside JavaScript`

Let me explain a bit, I have a master page named UserProfile.master which has a content placeholder linked to UserProfileWall.aspx. Now, I am trying to incorporate some additional JavaScript and a second CSS file in the userprofilewall page. However, whene ...

Whenever I launch my React web application, I consistently encounter a white screen when attempting to access it on my phone

After developing my web app in ReactJS and deploying it to the server, I've noticed that sometimes the screen appears white for the first time after deployment. However, when I reload the page, the app runs normally. I am hosting the backend and front ...

How can I randomly choose 5 TR items and show them to the user?

How can I randomly select and display 5 questions for the user? The rest of the questions should be hidden on the page and only 5 questions should be displayed. This is a sample code. I want the user to see 5 questions out of many questions when the page ...

Alert: A notification when navigating away from your site

Is there a way to notify users when they click on an external link that they are leaving your site? <div class="row"> <div class="col-lg-12"> <div class="form-group"> *If you need information on other applicable forms, you ...