The Cumulative Total of Index Values

Seeking guidance on improving my Problem Solving Skills and determining errors in my approach. The challenge lies in checking if an array contains numbers that sum up to a given total value - a task that seems simple but presents complexity for beginners.

To begin, I aim to create a function with two parameters: the array and the desired total amount.

const array = [10, 15, 7, 3];

function sumUpTotal(array, total) {

}

The next step involves iterating through the array using the forEach method to inspect each value individually.

const array = [10, 15, 7, 3];

function sumUpTotal(array, total) {
    array.forEach(value => {
        // logic goes here
    });
}

However, I find myself at a standstill when attempting to devise a method to confirm if certain values can combine to meet the required total. Any support in this regard would be highly appreciated.

The anticipated outcome is the identification of two numbers within the array that add up to the specified total.

For instance, if provided with [10, 15, 3, 7] and a total of 17, the expected result should be true as 10 + 7 equals 17.

Answer №1

To efficiently find unique sum pairs in an array, utilize the forEach() method for iteration and the includes() method to check for matching values ahead in the array. This approach prevents the generation of duplicate pairings by only considering values forward from the current iteration position.

The forEach() method provides access to both the value and the

index</code) of each iteration, enabling the use of the optional second argument <code>fromIndex
in includes() to restrict searches to values beyond the current index (achieved by passing index+1). When a match is found, an array of [value, difference] is added to the result array. The function returns an array of unique sum pairs or an empty array if no matches are identified.

const array = [10, -2, 15, 7, 3, 2, 19];

function findUniqueSumPairs(array, total) {
  let result = []
  array.forEach((value, index) => {
    let diff = total - value;
    if (array.includes(diff, index + 1)) result.push([value, diff]);
  });

  return result;
}

console.log(JSON.stringify(findUniqueSumPairs(array, 17)));
.as-console-wrapper { max-height: 100% !important; top: 0; }

Answer №2

To accomplish this task, utilize a Set in the following manner:

function findPair(array, target) {
  // create a new set
  const set = new Set();
  
  for(let i = 0; i < array.length; i++){
    const num = array[i];
    const complement = target - num;
    
    if(set.has(complement)) return [num, complement];
    else set.add(num);
  }
  
  return null;
}

const numbers = [6, 10, 4, 2];
const targetSum = 12;

console.log( findPair(numbers, targetSum) );

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 looking to incorporate a dropdown feature using Javascript into the web page of my Django project

According to the data type of the selected column in the first dropdown, the values displayed in the columns of the second dropdown should match those listed in the JavaScript dictionary below, please note: {{col.1}} provides details on the SQL column data ...

Are you ready to create a Modal Factory?

For a while now, I have been utilizing modals in various front-end frameworks to communicate with users in my applications. Typically, the process involves defining the modal's html and then rendering it through a click event. As my apps continue to ...

The tablesort feature is experiencing difficulty sorting tables with dynamically changing content

I have a question about sorting columns in a PHP file that calls a JS file. The PHP file contains two tables with the table sorter plugin implemented, but one of them works and the other doesn't. The working table is populated through an Ajax call, wh ...

Troubleshooting: Inability of Angular2 Component to access class property within template

Here is the code snippet that I am currently working with: post.component.ts: import { Component } from '@angular/core'; import { Router } from '@angular/router'; import { JobsService } from '../jobs.service'; @Component({ ...

Using the Google Chrome console, execute a command on each page within a specified website

While browsing a website, I noticed a bug that required me to manually run a JavaScript function each time I navigated to a different page in order for the site to work smoothly. Is there a way to automate this process upon page load? I am using Google C ...

Wait for the playwright to detect a specific and exact change in the inner text

There is a specific innerText that transitions from Loading to Play after 2-3 seconds. I want to wait for this change to happen before proceeding. Currently, I am using the following code snippet: let attempt = 0; let maxRetries = 4; let payerButtonStatus ...

When attempting to add objects to an indexedDB object store, an InvalidStateError is encountered

I have defined IndexedDB and IDBTransaction dbVersion = 1; var db; var dbreq; var customerData = { ssn: "444", name: "Bill", age: 35, email: "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d2b0bbbebe92b1bdbfa2b3bcabfcb1bdbf"& ...

Unable to link to '' because it is not recognized as a valid attribute of '' in Angular 2

I encountered an exception while working on my Angular 2 project and I'm struggling to figure out the cause. Below is the snippet of my code: ts: import {Component} from "@angular/core"; import {GridOptions} from "ag-grid"; import {RedComponentComp ...

Modifying the data attribute within the div does not result in a different image for the 360-degree spin view

My current project involves utilizing js-cloudimage-360-view.min.js to create a 360-degree view of images. I have successfully retrieved the images, but I am encountering difficulty in updating the images by clicking a button. index.html <!DOCTYPE html ...

Getting the id of a row from a v-data-table in VueJs

I am currently facing an issue with retrieving the id of a specific field from each row. I require this id as a parameter for a function that will be utilized in an action button to delete the row. Here is how my table template appears: <template ...

Tips for personalizing text and icon colors in the TableSortText element of Material-ui

My Goal: I aim to empower users with the ability to apply customized styles to my EnhancedTable component by utilizing a styles object containing properties like headCellColor, headCellBackgroundColor, bodyCellColor, bodyCellBackgroundColor, and more. The ...

conditionally manipulate colspan attribute with AngularJS

Is there a way to dynamically change the value of the 'th' colspan attribute based on a condition in Angular? I have attempted the following code, but it doesn't seem to be working. Can someone point out what might be incorrect here? <t ...

Unable to verify session using PHP file call via Ajax

I am utilizing DataTables Server Side to create a table. I am using login.php to fetch values from the database through Ajax. Below is the code snippet for DataTables: <?PHP session_start(); ?> <script type="text/javascript" language="javasc ...

Using async and await for uploading images

I am trying to create a post and upload an image if one is provided. If I successfully upload the image, everything works smoothly. However, if I do not upload an image, I encounter the following error: UnhandledPromiseRejectionWarning: TypeError: Cannot r ...

When attempting to upload a file using ajax, the $_FILES variable in PHP came

I am facing an issue with uploading images via AJAX where my PHP is not receiving the AJAX post. function handleFileSelect(evt) { files = evt.target.files; // FileList object $('.thumb-canvas' + filesId).css('display','bl ...

What is the most efficient method for designing this jQuery code to be reusable?

I am currently using dynamic Bootstrap popovers that are populated with content from my database. In PHP, it generates unique classes for each popover. My question is, when using jQuery, do I need to trigger the popovers individually? This is how I am cur ...

Creating a distinct numerical identifier and maintaining a tally in Java: What's the best approach?

Currently, I am coding a Java robot that extracts data from an excel file and uses it to create a unique username in another program. The only piece of information missing from the excel file is an ID number. To remedy this, I am attempting to create a 6- ...

Activate a function upon the clicking of a button by utilizing a directive in Angular.js

In my directive, there is a function called "myFunction()", and in the template, I have a button. When the button is clicked, I want to execute the function without using ng-click for specific reasons. Instead, I am looking to assign a class to the button ...

Angular 2 encountered a fatal error: Issues with parsing the template:

Here is the code snippet I am currently working with: <div class="container"> <div [hidden]="loggedIn"> <md-grid-list cols="6" [style.margin-top]="'20px'"> <md-grid-tile [colspan]="1"></md-grid-tile> I have already ...

What methods is Facebook using to manage their onbeforeunload confirmation dialog?

While using Facebook on the latest Chrome browser on my Mac, I observed an interesting behavior. When I began typing in a comment box and then clicked on another link or pressed the back button, a confirmation window popped up asking if I wanted to leave: ...