Find the index of two numbers in an array that equal a target sum

[https://drive.google.com/file/d/12qIWazKzBr1yJGpo1z106euXVJMKMwEa/view?usp=sharing][1]I am struggling to find the correct indices of two numbers in an array whose sum equals a target number provided as an argument. I attempted to solve this using a for loop, but my code is not returning the accurate indices. For example, if the first two numbers in the array are both 1 and the target is set as 2, I am getting the answer as [0,0], however, I want it to be [0,1]

let arr = [1,1,8,9,7,22,6]

var twoSum = function(nums, target) {
    for(i=0;i<nums.length;i++){
        for(j=i+1;j<nums.length;j++)
        if(nums[i] + nums[j]==target){
           
            return [nums.indexOf(nums[i]) , nums.indexOf(nums[j])]
        }

    }
};
console.log(twoSum(arr, 2))
i am expecting output as [0,1]
but i am getting output as [0,0]


  [1]: https://i.sstatic.net/n1jo7.png

Answer №1

Modifications:- Alter the output statement in your code

Script:-

let arr = [1,1,8,9,7,22,6]
var twoSum = function(nums, target) {
    for(i=0;i<nums.length;i++){
        for(j=i+1;j<nums.length;j++)
        if(nums[i] + nums[j]==target){
            return [i,j]
        }

    }
};
console.log(twoSum(arr, 2))

Result:-

node /tmp/fiXkoJ2VkT.js
[ 0, 1 ]

Note that if you are aiming for a total of 9, [0,2] and [1,2] both combinations result in 9 but only [0,2] will be displayed instead of [1,2]. This is because the algorithm checks the first element in all possible pairs before moving onto the second element.

Revised segment .. {your question}

https://i.sstatic.net/ZzR5o.png

Answer №2

The method known as indexOf is utilized to identify the initial appearance of a specific value within an array. In the event that both index 0 and index 1 contain the value 1, the method will solely indicate the position of 0 since it signifies the first occurrence of 1.

Check out the MDN Documentation

Solely retrieve the values of i and j themselves.

return [i, j];

Answer №3

let numbers = [1, 1, 8, 9, 7, 22, 6];

function findTwoSum(numbers, targetValue) {
  for (let i = 0; i < numbers.length; i++) {
    for (let j = i + 1; j < numbers.length; j++) {
      if (numbers[i] + numbers[j] === targetValue) console.log([i, j]);
    }
  }
}

findTwoSum(numbers, 2);

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

Is it possible to send a server response without requiring a callback function to be provided from the client side?

Clarifying the Issue When utilizing .emit() or .send() with a desire to confirm message reception (referred to as acknowledgements), the syntax typically involves: socket.emit('someEvent', payload, callback); The focus of this discussion is on ...

"Revolutionize Your Site with Endless Scrolling using q

I am currently in the process of developing a web application using create-react-app along with the packages Infinite-Scroller and qwest. (https://www.npmjs.com/package/react-infinite-scroller) (https://www.npmjs.com/package/qwest) This is how my code l ...

Can anyone provide tips on utilizing the .parent() method to generate a button that is exclusively associated with a single <div> element?

I'm working with the FullCalendar jQuery plugin and I'm attempting to create a 'weekends' button that will toggle weekends in the calendar display. The challenge I'm facing is that I have multiple calendar views on the same page, a ...

The JSON data lacks compatibility with the usage of track by functionality

I am working on a project that involves three connected select menus. The first one displays series names, the second one displays chapter numbers belonging to the series selected in the first menu, and the third one displays page numbers belonging to t ...

Learn the process of dynamically updating the source of an HTML5 video

Currently, I am working on a project that involves dynamically loading multiple videos onto a webpage. The structure of my HTML is quite straightforward - it consists of a single video tag. <video controls preload width="520" height="350" id="video"> ...

Utilize the RRule library in JavaScript by incorporating the rrule.min.js script

I am having trouble integrating the library https://github.com/jakubroztocil/rrule into my website. Whenever I try to do so, I encounter the error: Uncaught SyntaxError: Unexpected token { I have attempted the following: <!DOCTYPE html> <html ...

Modifying hidden field values with JavaScript does not carry over to the server side in Chrome

I created a custom user control that contains a hidden field which is set when a node is clicked on a Tree View Hierarchy control. The following function is responsible for handling the click event of the Tree View: function HandleTreeClick(evt) { va ...

Tips for repeatedly clicking a button over 50 times using Protractor

Is it possible to click the same button more than 50 times using a loop statement in Protractor? And will Protractor allow this action? Below is my locator : var nudge= element(by.xpath("//a[@class='isd-flat-icons fi-down']")); nudge.click(); ...

Attempting to access a structure member that is of an incomplete type is causing a dereferencing pointer error

I have reviewed similar questions with related issues, however, none of the proposed solutions have resolved my particular case. The issue at hand involves my attempt to construct a stack with dynamic memory allocation, using the following struct: struct ...

Keep rolling the dice until you hit the target number

Currently, I am in the process of learning JavaScript and one of my projects involves creating a webpage that features two dice images, an input box, and a button. The objective is for users to input a value, click the button, and then see how many rolls i ...

Customize the appearance of every other column in an asp gridview

Looking for help with formatting rows and columns in an ASP GridView. The rows are automatically colored alternating, and I want to make the content in every first column bold and every second column normal. I have heard about using CSS nth-child() to achi ...

Determine the mean value from an array of JSON objects in an asynchronous manner

Can you help me calculate the average pressure for each device ID in this JSON data set? [ { "deviceId": 121, "Pressure": 120 }, { "deviceId": 121, "Pressure": 80 }, { "deviceId": 130, "P ...

tips for transferring a javascript function value to a label within a webform

Currently, I am in search of the latitude and longitude coordinates for a specific address input by the user. Upon clicking a button, the script provided below is triggered to display an alert with the latitude and longitude values: <script type="text/ ...

The arrow function in Jest is missing a name property

Currently, my setup includes: node.js: 9.8.0 Jest: 23.4.2 ts-jest: 23.1.3 typescript: 2.9.2 While attempting the following in my *.test.ts files: const foo = () => 'bar'; console.log(foo.name); // '' foo contains the name pro ...

Is there a way to send a Map object to a script file using EJS?

I am facing an issue with passing a Map object to my client-side code. I have successfully used EJS and JSON.stringify(...) in the past for arrays, but it doesn't seem to work for Maps. When I try to console.log(myMap.keys()), I receive the following ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

Securing routes with passport.js in a MEAN Stack setting

I am facing an issue with securing individual routes in my admin panel using passport.js. The user signup functionality is working fine, and I am able to login successfully. However, the req.isAuthenticated() function always returns false, preventing me fr ...

How can I retrieve the position of a specific string within a redis list?

In my game, I have a list of current players and keep track of the turn with an integer. When a player leaves, they are removed from the list, and in some cases, I need to adjust the turn value as well. I've observed that if a player's index is ...

Having trouble with SCSS styles not being applied after refactoring to SCSS modules?

Currently, I am in the process of restructuring an application to ensure that component styles are separated from global styles using CSS modules. However, I have come across an issue where the styles are not being applied correctly. The original code sni ...

Using React JS to create an interval with an API connection

Is there a way to use setInterval to make an API call once every hour? I would like to set this up in my code. componentDidMount() { fetch(fullURL) .then((response) => response.json()) .then((responseJson) => { // console.log(respons ...