Two approaches to discovering a set of items within an array that yield contrasting outcomes

Two different approaches are being used to solve this problem.

"Determine a pair of numbers in an array that add up to a specific value"

However, these methods are yielding distinct outcomes. What could be the reason behind this discrepancy? One method identifies 5 pairs while the other finds 6 pairs - why is there such variation?

The first approach involves a nested loop.

export function pairElements(arr, arg) {
  var pairArr = arr.slice(); // create a duplicate array
  var result=[];
  for(var i = 0; i < pairArr.length; i++) {
    for(var j = i + 1; j < pairArr.length; j++) {
      if(pairArr[i] + pairArr[j] == arg) {
        let pair = [pairArr[i], pairArr[j]];
        result.push(pair);
     }

   }
 }
 return result;
} 

pairElements([1,4,2,3,0,5,4,3], 7);
result = [ [4, 3], [4, 3], [2, 5], [3, 4], [4, 3] ];

The second approach employs the reduce method.

 function pairReduce(arr, arg) {
  var pairArr = arr.slice();
  var result=[];
  return pairArr.reduce( function (a,b,index){
      let pair = [];
      let search = arg - b; 
      let searchIndex = pairArr.indexOf(search);

      if ( searchIndex != -1 && searchIndex != index){
         pair.push(b, search);
         result.push(pair);
      }
      return result;
  }, 0);
}

pairReduce([1,4,2,3,0,5,4,3], 7));
result = [ [4, 3], [2, 5], [3, 4], [5, 2], [4, 3], [3, 4] ]

Answer №1

One simple yet effective method entails examining each element in the array and searching through the remaining elements for its pair to obtain the desired result when added together.

For instance, consider the following input:

arr = [1,4,2,3,0,5,4,3]
res = 7

Initially, the number 1 (the 0th element) is evaluated. Subsequently, each subsequent element (ranging from 4 to 3) is added to it and compared against 7. In this case, there is no occurrence of 6 in the array, resulting in no match found.

Moving on to the evaluation of the number 4, we encounter some interesting findings:

4 + 2 = 6 // not a pair  
4 + 3 = 7 // a pair found!
4 + 0 = 4 // not a pair
4 + 5 = 9 // not a pair
4 + 4 = 8 // not a pair
4 + 3 = 7 // another pair found!

Through this search process, two sets of pairs with identical elements - [4, 3] are identified. Moving past the obvious (2, 5 pair), the examination then shifts to 3:

3 + 0 = 3; // -
3 + 5 = 8; // -
3 + 4 = 7; // +
3 + 3 = 6; // -

An observable pattern emerges during this iteration: the current evaluation concludes by identifying the pair of first 3, second 4. Both choices appear to align with the specified criteria.

=====

The alternative approach introduces an unconventional perspective. The author's interpretation considers indexOf as a straightforward operation with constant time complexity (which is not accurate) and overlooks a crucial distinction: indexOf inherently targets the first element adhering to its predicate.

As exemplified, during the execution of the reduce function over the initial 4 in the array, indexOf verifies the presence of

3</code - leading to the discovery of the first <code>3
encountered:

// reduce on b = 4, index = 1
search = 7 - 4; // 3
searchIndex = arr.indexOf(3); // 3

However, this particular pairing resurfaces when evaluating the first occurrence of 3</code (as <code>indexOf also identifies the first 4).

// reduce on b = 3, index = 3
search = 7 - 3; // 4
searchIndex = arr.indexOf(4); // 1

Intriguingly, despite the redundancy within this set, it unintentionally compensates for neglecting to reevaluate the 'first instances' with respect to both the subsequent 4 and 3.

// reduce on b = 4, index = 6
search = 7 - 4; // 3
searchIndex = arr.indexOf(3); // 3

// reduce on b = 3, index = 7
search = 7 - 3; // 4
searchIndex = arr.indexOf(4); // 1

Notably, further pairs are identified while one remains unnoticed: the last elements of the array lack corresponding pairs.

Can the secondary approach be rectified? Certainly, a slight enhancement involves providing the secondary argument into indexOf:

let searchIndex = pairArr.indexOf(search, index + 1);

...however, this adjustment solely caters to arrays comprising unique elements. Otherwise, resorting to an explicit loop would essentially transform this strategy into a far more complex rendition of the initial one.

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

In the event that the $state cannot be located, redirect to a different URL using Ui

Our platform is a unique combination of WordPress backend and AngularJS frontend, utilizing ui.router with html5 mode turned on and a base href="/" due to the stack sites being in the root of the site. We are currently facing an issue: 1) Previously, whe ...

Get the unique _id value of the object once it has been added to an established collection

Recently, I encountered a mongodb document with the following schema: class: String, class_teacher: String, students: [ { student: String, marks: number } ] In this scenario, when adding a new student to the collection, each studen ...

Automatic resizing of line charts in Angular with nvd3

I'm currently utilizing AngularNVD3 directives. Referencing the example at: https://github.com/angularjs-nvd3-directives/angularjs-nvd3-directives/blob/master/examples/lineChart.with.automatic.resize.html <!-- width and height have been removed f ...

What could be causing the images to not display on my HTML page?

My program is designed to display an image based on the result of the random function. Here is my HTML: <div> <h2>Player 0:</h2> <div id="MainPlayer0"></div> </div> Next, in my TypeScript fi ...

Do you notice a discrepancy in the number returned by Javascript's Date.getUTCDate() when the time component is set to

Consider the following code snippet: const d = new Date('2010-10-20'); console.log(d.getUTCDate()); If you run this, the console will output 20. However, if you modify the code like so: const d = new Date('2010-10-20'); d.setHours(0, ...

Printing a Page Using Angular 5

Is there a way to print a specific section of my website with Angular 5? I've searched online for a solution, but it seems like most options are tailored for Angular. Any advice? ...

Refresh HTML with JSON/AJAX

Ever since I discovered JSON for handling AJAX functionality in my rails applications, I've been hooked. Using RJS to render HTML just didn't sit right with me as it felt like it was violating the MVC pattern. My first project that heavily utiliz ...

Should a MEAN stack app require the use of two servers in order to run?

Currently, I am in the process of developing a MEAN stack application which involves using MongoDB, ExpressJs, Angular 6, and NodeJs. One issue I am facing is determining whether two servers will be necessary to run the app simultaneously. Specifically, o ...

Function Errors, How to Fix Them?

I've recently developed a tool for character creation within a new video game. However, I'm currently facing an issue: When it comes to assigning points in Magic Power or Weapon Power for the Warrior and Wizard characters, there seems to be a p ...

Sending an array of arrays from JavaScript to a Spring MVC controller via AJAX

Having a bit of trouble with passing arrays within arrays. The first example below shows a simple array being passed successfully. However, when attempting to pass an array of arrays in the second example, it doesn't seem to work. Any suggestions on h ...

How to insert a value using jQuery Minicolors in an HTML document?

While I found similar topics on Stackoverflow, none exactly match my issue. I am currently incorporating jquery Minicolors into my project: https://github.com/claviska/jquery-miniColors/ Everything is functioning properly, but I simply need to accomplish ...

The HTML content retrieved through an ajax service call may appear distorted momentarily until the JavaScript and CSS styles are fully applied

When making a service call using ajax and loading an HTML content on my page, the content includes text, external script calls, and CSS. However, upon loading, the HTML appears distorted for a few seconds before the JS and CSS are applied. Is there a sol ...

HTML dropdown menu to trigger an action with the submitted URL

I need assistance creating a menu of options with corresponding URL actions. Here is the structure I have in mind: <form> <select> <option value="1">1</option> <option value="2">2</option> <option value="3 ...

Struggling to understand how React js interacts with CSS files

While reviewing a React JS project, I came across some confusing CSS classes in the file. Classes like '.cards__item', '.cards__item__pic-wrap', and '.cards__item__img' were being referenced, but they weren't present in t ...

Utilize the identical mathematical equation across various jQuery values

I have a JavaScript code that calculates the size of circles on the screen based on multiple variables. Currently, I am repeating the same equation for each circle by numbering all the variables accordingly. Is there a way to simplify this process and run ...

Using Coffeescript to implement mixed objects with magic getters and setters like in Harmony, node-proxy, and other Javascript proxies

I am looking to create a proxied object with methods and private variables attached to it. This means having normal object properties: foo = {} foo.bar = "baz" foo.boo = "hoo" along with some prototypes: foo.setPrivateThings = function(value){ if (valu ...

Using JavaScript to pass the href attribute value

On my HTML page, there are multiple links that reload the page when clicked. I want to capture the href value of each link the user clicks and store it in a variable called xhash: Here is the HTML: <a href='#taba' id='passid'>Li ...

When using NextJS components, they function properly in development mode but encounter issues in production mode

I have encountered a problem with the 'Highlight' component from the 'react-highlight' library while working on a project using NextJS in both development and production modes. During development mode, the component appears as expected ...

Submit both file data and form data

I am encountering an issue where I can only pass either my form data or data from an uploaded file, but not both simultaneously. Here is the JavaScript code I am using to retrieve the data: var form = document.getElementById('AddDocs'); var dat ...

The retrieval of data from AWS Dynamodb in Node.js is not done synchronously

I recently started working with Node.js and DynamoDB. I created a Node.js SDK to retrieve a single row from a DynamoDB table. The data is being fetched correctly, but there is a delay which is causing an error. Below is a snippet of my code: var AWS = re ...