Using JavaScript to retrieve and compare element values for a total sum

Given two arrays, the goal is to determine if any two numbers in the array add up to 9.

The function should return either true or false.

For example:

array1 [1, 2, 4, 9] has no pair that sums up to 9, so it returns false

array2 [1, 2, 4, 5] does have a pair (4 and 5) that adds up to 9, so it returns true

To achieve this, you can use the following JavaScript function:


function hasPairWithSum(arr, sum) {
    var len = arr.length;
    for(var i=0; i<len-1; i++) {
        for(var j=i+1; j<len; j++) {
            if (arr[i] + arr[j] === sum)
                return true;
        }
    }

    return false;
}

console.log(hasPairWithSum([1, 2, 4, 9], 9));

console.log(hasPairWithSum([1, 2, 4, 5], 9));

If you're looking for an alternative approach to solving this problem, feel free to experiment further!

Answer №1

function FindingPair(arr, total) {
  return arr.some((num1, index1) => arr.some((num2, index2) => num1 + num2 === total && index1 !== index2))
}

console.log(FindingPair([1, 2, 4, 9], 9));
console.log(FindingPair([1, 2, 4, 5], 9));

Answer №2

This particular method offers a quick and efficient solution.

function findPair(arr, S) {

  var hashTable = {};

  // Iterate through each element in array
  for (var i = 0; i < arr.length; i++) {

    // Calculate the difference between S and the current element
    var diff = S - arr[i];

    // Check if this number exists in the hash table
    // If it does, then we have found a pair of numbers that add up to S
    if (hashTable[diff.toString()] !== undefined) {
      return true;
    }

    // Add the current number to the hash table
    hashTable[arr[i].toString()] = arr[i];

  }

  // Return false by default
  return false;

}

console.log(findPair([3, 5, 2, -4, 8, 11], 7));

This approach leverages the use of hash tables.

Answer №3

Here is an innovative method utilizing a generator function combined with recursion to create pairs, along with an includes function that utilizes an iterator and predicate for testing items against the generator:

function* generatePairs(arr) {
  if (!arr.length) return false;
  const [head, ...tail] = arr;
  for (let value of tail) {
    console.log(`[${head}, ${value}]`);
    yield [head, value];
  }
  yield* generatePairs(tail);
}

function checkIfIncludes(iterator, predicate) {
  let result = iterator.next();
  while (!result.done) {
    if (predicate(...result.value)) {
      return true;
    }
    result = iterator.next();
  }
  return false;
}

const calculateSumEquals = sum => (num1, num2) => num1 + num2 === sum;
const pairValuesEqual = ([x, y]) => (m, n) => x === m && y === n;

console.log(checkIfIncludes(generatePairs([2, 4, 9]), calculateSumEquals(9)));
console.log(checkIfIncludes(generatePairs([2, 4, 5]), calculateSumEquals(6)));
console.log(checkIfIncludes(generatePairs([2, 4, 5]), pairValuesEqual([2, 5])));

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

What causes the variance in outcomes between employing a literal string versus a local variable?

Here is a loop that I am working with: for (var key in criteria) { var exists = Object.keys(item).some(function(k) { return item[k] === "Test"; }) } Initially, this loop functions as expected and returns 15 trues based on the number of i ...

Guide to animating the height of a div using jQuery:

I'm hoping to create a cool animation effect where a certain part of a div expands to 100% width when clicked, and then reverts back to its original height on a second click. I've tried writing some code for this, but it's not working as exp ...

subscriptions to behavior subjects may not function properly across all components

When setting up my global service, I instantiate a BehaviorSubject variable dataWorkflowService: export class CallWorkflowService { url = 'http://localhost:3000/'; selectedNode : BehaviorSubject<Node> = new BehaviorSubject(new Node(&a ...

What is the best way to manage a session using JavaScript?

Currently developing a website that initially hides all elements except for the password box upon loading. Once the user enters the correct password, all webpage elements are revealed. Seeking a solution to keep the elements visible on reload by utilizing ...

Solving required packages in Express server

I am encountering difficulties with resolving dependencies on my express server. Below is the structure of my project: Calculator --dist ----app -------calculator.js -------server.js --node_modules --src ----app --------calculator.js --------server.js -- ...

What is the most effective method to include JSON data containing various IDs at the end within an $http.get() request in AngularJS?

I'm facing a challenge with displaying JSON items that have an array of different ids at the end of the URL (/api/messages/:messageId). For instance, accessing /api/messages/12345 would return {"subject":"subject12345","body":"body12345","id":"12345"} ...

How can I deactivate the today button in the angular-ui bootstrap datepicker popup?

Currently, I am working with two dates: StartDate and EndDate which are being managed using the angular-ui-bootstrap datepicker. When a user selects a StartDate (which must be greater than today's date), I want to ensure that the min-date of the EndD ...

Steer clear of using multiple returns in a loop in JavaScript by utilizing async/await to eliminate the callback pyramid or callback hell

My code consists of multiple return blocks, such as the SignUp() function. connectors.js const connectors = { Auth: { signUp(args) { return new Promise((resolve, reject) => { // Validate the data if (! ...

What could be the reason why my JavaScript code for adding a class to hide an image is not functioning properly?

My HTML code looks like this: <div class="container-fluid instructions"> <img src="chick2.png"> <img class="img1" src="dice6.png"> <img class="img2" src="dice6.png" ...

Encountering a frustrating internal server error 500 when attempting to insert values from JavaScript into SQL Server within Visual Studio

Here is a JavaScript code that calls a C# webmethod: var _data = { '_mStart': document.getElementById("St_Period").value, '_mEnd': document.getElementById("En_Period").value }; $.ajax({ type: "POST", url: "maps.aspx/my ...

Is there a simple way to display all the data from a JSON object even if the contents are unknown beforehand?

Greetings! I am Pearson's dictionary api. Here is a glimpse of what I receive from an api call: { "status": 200, "offset": 0, "limit": 10, "count": 10, "total": 135, "url": "/v2/dictionaries/entries?headword=dog", "results": [ { ...

Is there a significant distinction between value and defaultValue in React JS?

React's homepage features the final illustration (A Component Using External Plugins) with a textarea: <textarea id="markdown-content" onChange={this.handleChange} defaultValue={this.state.value} /> While typing, the ...

Tips for extracting values from a PHP array using JavaScript

Assuming we have a PHP array named $decoded: $decoded = array( 'method' => 'getFile', 'number' => '12345' ); The data from this array will be passed to a JavaScript function called get(params). funct ...

Ensuring data integrity with form validation using Jquery prior to submitting an

After researching various forums and referencing one, I am still unable to find a solution for my issue. My query is: When I click a button, it triggers a function that includes validation. Upon successful validation, I attempt to post data with an Aj ...

While attempting to insert a sublist into a Guava table within a nested loop, the operation results in

As I traverse a multidimensional array, I generate random values in the third nested loop and add them to a list. Each sublist of this list is then added into a Guava table. The code runs without errors until I try to print all the contents of the table, ...

What is the best way to add a property and its value to objects within an array, especially those which do not currently have that specific property?

My goal is to: Iterate through the peopleData array, add a property named 'age' and assign it a value of '-' for any objects in the array that do not have the key 'age' const peopleData = [ { name: "Ann", age: 15, email: ...

Strategies for dynamically altering Vue component props using JavaScript

for instance: <body> <div id="app"> <ro-weview id="wv" src="http://google.com"></ro-weview> </div> <script> (function () { Vue.component("ro-webview", { props: ["src"], template: ` <input type="t ...

Harness the power of a NUXT component on a different website

Currently, I have a fully functional NUXT application that consists of numerous pages and components operating in `universal` mode. My challenge now is to render one of these components on a separate static HTML website. Exporting a component from a stand ...

Effortlessly saving money with just one click

I have a search text box where the search result is displayed in a graph and then saved in a database. However, I am facing an issue where the data is being saved multiple times - first time saves properly, second time saves twice, third time three times, ...

Unable to transform object into a primitive value using imported JSON data

https://i.sstatic.net/HcY5M.png I am currently working on creating a Vuetify component dynamically within a Nuxt project, as discussed in this Stack Overflow thread (Using different text values with Vuetify component). To achieve this, I am importing and ...