Is it possible to keep adding the keys of an array to themselves until reaching a specified limit

Given an array var ary = [5,10,28,50,56,280], I am exploring the idea of generating all possible combinations or subsets of this array until a certain threshold is reached.

The objective is to store this limit in a variable and collect all the elements being added into an array.

var ary = [5,10,28,50,56,280];
var limit = 11;
var result = [];
var addends = [];

for( var i = 0; i <= ary.length; i++ ){
if( ary[ i ] > limit ){
result.push( ary[ i ] );
addends.push( ary[ i ] );
}
else if( ary[ i ] + ary[ i ] > limit ){
result.push( ary[ i ] + ary[ i ] )
addends.push( ary[ i ] );
addends.push( ary[ i ] );
}
}

Is there a systematic approach that can be applied regardless of the size of the array or the value of limit?

Answer №1

It seems like you're looking to explore all possible permutations:

function permutationFinder(arr) {
  var results = [];

  function permutate(array, memo) {
    var current, memo = memo || [];

    for (var i = 0; i < array.length; i++) {
      current = array.splice(i, 1);
      if (array.length === 0) {
        results.push(memo.concat(current));
      }
      permutate(array.slice(), memo.concat(current));
      array.splice(i, 0, current[0]);
    }

    return results;
  }    
  return permutate(arr);
}

var allPermutations = permutationFinder([7,15,22,40,45,90]);
console.log(allPermutations);

With this approach, you can modify the code to accommodate your unspecified requirement about a "limit".

This code snippet was borrowed with admiration from @delimited on Stack Overflow: Permutations in JavaScript?

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

Initiate magnific popup only when the body class meets certain criteria

I am currently utilizing a plugin called magnific popup and I have a requirement to display a video when a user navigates to the site (while also ensuring it doesn't show every time). To achieve this, I am using localStorage. The code for this functio ...

Using AngularJS controller to implement filtering functionality

I am a beginner at using Angular and have successfully implemented a filter to translate text for localization in my HTML view: <input type="button" class="btn btn-link" value="{{'weeklyOrdersPage.reposting' | translate}}" ng-click="sortBy(&a ...

Issues with testing incorporating jest, react, webpack, and SVG

I recently delved into the world of React development, but I've hit a snag when trying to run a test with an SVG file. You can find the code in my GitHub repository https://github.com/alejomongua/react-playground. Upon running npm run test, I encoun ...

Change the term to its corresponding translation

I have developed an Ionic Multilingual App that includes a select feature. Within this select, choosing a specific option disables certain page elements. However, I am facing an issue where one of the elements needs to change its text based on the selected ...

Transforming a THREE.js shader into a PIXI.js shader

I am currently exploring the world of PIXI.js and custom Shaders, and I must admit, it's a bit overwhelming for me. I came across a GLSL Shader (created by DonKarlssonSan) that I would like to convert to PIXI.js in order to compare performance. Any as ...

Creating animated content with Blender and Three.js

Recently, I acquired a 3D model of an umbrella with a pre-existing animation that showcases its opening and closing. After importing it into my project using Three.js, I played the animation. To my surprise, what I thought was one animation turned out to b ...

Adjust the appearance using Timeout within a React component

I am facing a challenge with updating the style in React - specifically, the opacity of a Div element is not updating despite successfully updating the opacity in a timeout event. import React from 'react'; function PortItem(props){ let style ...

"Create a New Browser Tab When User Interacts with a Hyperlink leading to an External Website

I am currently working on a recommendations app built with React and I want to enable users to navigate to external websites when they click on a component that displays information about that website. At the moment, I have implemented a wrapper that, upo ...

Creating a password hint in jQuery using asterisks: a step-by-step guide

For instance: http://jsfiddle.net/na2tD/ At the moment, the password field does not display asterisks because the 'type' attribute is set to "text" instead of "password". Is there a way to use jQuery hint and still have asterisks displayed for t ...

Load a CSV document and add its contents to an existing array

My CSV file has a specific format: Image Id,URL,Latitude,Longitude 17609472165,https://farm8.staticflickr.com/7780/17609472165_c44d9b5a0e_q.jpg,48.843226,2.31805 11375512374,https://farm6.staticflickr.com/5494/11375512374_66a4d9af6c_q.jpg,48.844166,2.376 ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

Creating customizable Isotope objects using custom CSS margins that are influenced by the child-nth selector and JavaScript

My recent project involved creating a simple .isotope gallery, and when viewing the selected #portfolio-wrap container in Chrome Dev Tools, here is how it appears: Unfortunately, I am unable to upload three links here. Please visit this link for more info ...

Managing the addition of new data to an already established array with PHP

I'm currently working on a function called getPageContent that organizes sections, sub-sections, and resources within them. However, I'm facing an issue where the Volvo XC60 is mistakenly placed under the Vauxhall section instead of Volvo. Can an ...

Issues with PHP server handling JSON files

I'm having some trouble retrieving server data to display in a table on my iPhone. The process involves the standard flow of server - php_interface - iOS. Initially, I attempted to use an echo json_encode(array) setup, but ran into issues with populat ...

The significance of the dollar sign in ReactJs

Why is the $ symbol placed after the 'add' and 'tab' in the activeKey and the tab in the given code snippet? addNum=0; onAdd=()=> { this.addNum++; let panes=Array.from(this.state.panes); let activeKey=`add$ { this.addNum ...

Ways to remove all attributes from a JSON data type

In my code, I am working with the following object: [ { "Name": "John Johnsson", "Adress": "Linkoping", "Id": 0, "Age": "43", "Role": "Software Engineer" }, { &qu ...

Error: JSON parsing error encountered due to an unexpected token 'U' while trying to read a file with

Currently, I am utilizing Node.js version 12.14.1 and encountering a problem while attempting to parse a JSON file that includes the \U0001f970 character. The file's content that needs to be read and parsed is as follows: {"randomKey": ...

Retrieving the maximum number and its corresponding name from an object using JavaScript

Check out my cool react app at this link: https://i.stack.imgur.com/9VpCd.jpg I've been working on a function to find the highest and lowest latitude along with the corresponding city names. Currently, I have successfully retrieved the latitudes but ...

Challenges encountered when retrieving parameters from union types in TypeScript

Why can't I access attributes in union types like this? export interface ICondition { field: string operator: string value: string } export interface IConditionGroup { conditions: ICondition[] group_operator: string } function foo(item: I ...

When setting properties on the Object or Array prototype in JavaScript, it disrupts the functionality of brackets

Similar Question: Adding functions to the Array class in JavaScript causing issues with for loops While it may not be best practice, I want all objects to have this specific function when including a certain piece of code. I find it strange that when ...