Determine all the unique pairs of different integers from an array of integers arr that add up to a specific target sum

Discovering pairs of distinct integers in an array that sum up to a target value can be challenging. If successful, you'll need to organize these pairs in ascending order within arrays. In case no such pairs exist, an empty array should be returned.

I attempted to solve this problem using a specific approach, but unfortunately, it didn't yield the desired results.

function findPairs(arr, target) {
  let result = []
  for (let i = 0; i <= arr.length - 1; i++) {
    for (let j = i + 1; j < arr.length - 1; j++) {
      if (arr[i] + arr[j] === target) {
        result.unshift(arr[i], arr[j])

      }

    }

  }
  return new Array(result)
}
console.log(findPairs([3, 7, 8, 4, 5, 9], 12)) // [[3,9],[4,8],[5,7]]

console.log(findPairs([1, 2, 3, 4], 8)) // []

Answer №1

Here is a potential solution that could assist the original poster in restarting their approach.

The process involves creating a copy of the passed array and then systematically emptying it by removing items one by one. Each iteration involves checking for matching pairs within the array and updating it accordingly.

A detailed explanation of the implementation can be found in the provided JavaScript code snippet below.

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

Tips for utilizing window.scrollTo in order to scroll inside an element:

I'm experiencing an issue where I have a vertical scrollbar for the entire page, and within that, there's an element (let's call it 'content') with a max-height and overflow-y scroll. The 'content' element contains child ...

Three Conditions that Must be Fulfilled for Jquery CSS Selection

I have a challenge to create a CSS selector that demands the fulfillment of three specific criteria in order to trigger an action. $('div[class*="clickout"]') $('div[class*="preferred"]') $('div[class*="test"]') My goal is t ...

sending a collection of elements to a jQuery function

I am puzzled by why this function is not working as expected when passing an array of items to it. My intention with the for-loop is to change the status of the child ctrl element to either '+' or '-'. An error occurred: Uncaught Typ ...

Continuously looping through the function based on availability in Symbol ES6

When using the ES6 Symbols iterator, I found that I needed to call the next function each time to print the next item during iteration. Below is the code snippet: var title = "Omkar"; var iterateIt = console.log(typeof title[Symbol.iterator]); var iter ...

Steps to make ng-packagr detect a Typescript type definition

Ever since the upgrade to Typescript 4.4.2 (which was necessary for supporting Angular 13), it appears that the require syntax is no longer compatible. Now, it seems like I have to use this alternative syntax instead: import * as d3ContextMenu from ' ...

Tips for implementing lazy loading for a section of a template in Angular 2

I have an Angular 2 component that has several sub-components within it. Some of these sub-components are expensive to load and may not always be necessary, especially if the user doesn't scroll far enough down the page. Although I am familiar with l ...

Tips on incorporating personalized javascript functions into Durandal

I am currently working on my first project using the Durandal framework to create a basic website. I have encountered an issue while trying to incorporate a simple JavaScript function. My goal is to execute the function after the DOM has loaded, but I am u ...

Error message: The variable datepicker_instActive is not defined within Jquery-ui Datepicker

Having trouble with a Rails + Angular app where I've implemented the jquery-ui datepicker. The console is showing an error that says: TypeError: datepicker_instActive is undefined if(!$.datepicker._isDisabledDatepicker( datepicker_instActive.inline? ...

How to avoid property sharing in Angular recursive components

I am currently working on a recursive component that generates a tree structure with collapsible functionality. However, I am facing an issue where the state variable active is being shared among child components. Is there a way to prevent this from happen ...

Using Double Equal in a JavaScript For Loop

I'm struggling to comprehend why utilizing a double equals (or even a triple equals) in the condition of a for loop doesn't function as expected. Consider this example: for (i = 1; i == 5; i++){ console.log(i) } When I replace == with <= ...

What is the best approach to creating a Typescript library that offers maximal compatibility for a wide range

My Vision I am aiming to develop a versatile library that can cater to both JavaScript and TypeScript developers for frontend applications, excluding Node.js. This means allowing JavaScript developers to utilize the library as inline script using <scri ...

Sorting with jQuery UI - execute action on drag start and clear on drop

I am currently working with two blocks: one is "draggable" and the other is "sortable". My goal is to add a background color to a div when dragging an item from "sortable" and remove it once the dragging stops. Below is my JavaScript code: $(".sortableL ...

Cookies are exclusively established in Chrome, with no presence in Safari, Mobile Chrome, or Mobile Safari

When using desktop browsers (specifically Chrome), my sign up and sign in endpoint works perfectly fine. However, I encounter a server timeout issue when attempting to sign up or sign in using a mobile browser. This problem arises from the session cookies ...

Vuetify: Utilizing condition-based breakpoints

Here is the layout that I am working with: https://i.stack.imgur.com/qlm60.png This is the code snippet that I have implemented: <template> <v-card> <v-card-text> <v-container grid-list-xl fluid class="py-0 m ...

Sorting() Multi-dimensional Arrays with value change beforehand

I am looking for a way to sort a multidimensional array, but first I need to change the format of the values for sorting and then revert them back to their original format. Here is my multidimensional array: $db = [['1','00:01:13.145' ...

Is it true that node.js arrays can be considered as hashmaps?

Surprisingly, this code is functioning properly in node.js: var arr = new Array(); // also works: var arr = []; arr[0] = 123; arr['abc'] = 456; arr; // node.js: [ 123, abc: 456 ], chrome: [123] I've always believed that an array preserves ...

Updating an Angular Signal established by an RxJs stream within a service: Best practices

Within my Angular application, there is a service class named ProjectsService that handles all project-related data. It effectively manages a feed of tasks and includes functionality for liking those tasks as well. The service contains two important signal ...

Failure to transfer text to POST variable

Having an issue with line 18 in the HTML code below not carrying over to $_POST['storename'] after hitting Submit. All other text fields are transferring correctly. The only distinction is that this field auto-fills data from a database using PHP ...

Anomalous Behavior of Strings within Array - Exploring the Expo Application

Although the following lines of code appear to be self-contained and separate from the rest of the project, I can provide more context if needed. Now, let me share with you a bizarre issue that has left me puzzled - even after years of working with JavaScr ...

Checkbox inputs with activated labels causing double events to fire

Creating round checkboxes with tick marks dynamically and appending them to id="demo" on the click of two buttons that invoke the get(data) method is my current goal. The issue arises when both buttons are clicked simultaneously, as the checkboxes do not ...