Issue with retrieving the positions of two numbers in an array

I encountered a challenge:

I have an array of integers nums and an integer target. My goal is to find the indices of two numbers in the array that add up to the specified target.

Example 1:

Input: nums = [2,7,11,15], target = 9
Output: [0,1]
Output: This is because nums[0] + nums[1] equals 9, so we return [0, 1].

After experimenting with some code utilizing set and Map, I was able to get the sum of values in the array.

However, my current challenge lies in returning the indices.

const arr = [{key1: 2}, {key1: 7}, {key1: 11}, {key1: 15}];
const k = 9;
const valueSet = new Set(arr.flatMap((x) => Object.values(x)));
const valueArray = [...valueSet];

valueArray.forEach((v1, i1) => {
    for (let i2 = i1 + 1; i2 < valueArray.length; i2++) {
        if ((v1 + valueArray[i2]) === k) {
            // Return the indices
            return valueArray[i2];
        }
    }
});

Answer №1

To find the precise combination of indexes that will yield the desired sum, you must diligently parse through the data.

Feel free to refer to the code snippet below for assistance:

const arr = [{ key1: 2 }, { key1: 7 }, { key1: 11 }, { key1: 15 }];
const k = 9;
let valueSet = new Set(arr.flatMap((x) => Object.values(x)));
let valueArray = [...valueSet];

let indices;
let isFound = false;
// valueArray.forEach((v1, i1) => {
for (let i1 = 0; i1 < valueArray.length && !isFound; i1++) {
  for (let i2 = i1 + 1; i2 < valueArray.length && !isFound; i2++) {
    if ((valueArray[i1] + valueArray[i2]) === k) {
      //Determine and display the Indices
      indices = [i1, i2];
      isFound = true;;
    }
  }
}
console.log(indices);

Answer №2

The solution provided by Nitheesh is effective. To understand why your initial approach did not work, here's an explanation:

When using forEach to iterate over an array, the callback function is invoked for each element in the array. Using return within a forEach loop only exits the current element's callback, not the entire iteration. Therefore, a return in a forEach loop is akin to a continue in a traditional for loop.

For more information, you can refer to this source.

Answer №3

To start, extract the values from the array using the keys

 [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
. Next, iterate through the values array and check if the sum of two elements equals the target value. For example, (7 + 2 == 9).

const arr = [{key1: 2},{key1: 7},{key1: 11},{key1: 15}];
const k = 9;
nums = arr.map((o) => {
  return Object.values(o)[0]
})

const twoSum = (nums, target) => {
    for(let i = 0; i < nums.length; i++){
        for(let j = i+1; j < nums.length; j++){
            if(nums[i] + nums[j] == target){
                return [i, j]
            }
        }
    }
};

console.log(twoSum(nums, k))

Answer №4

Here is a possible solution:

function findIndices(target, array) {
  let output = [];

  for (let i = 0; i < array.length; i++) {
    for (let j = 0; j < array.length; j++) {
      if (array[i] + array[j] === target) {
        return (output = [array[i], array[j]]);
      }
    }
  }

  return output;
}

function searchIndices(target, array) {
  let output = [];

  for (const num1 of array) {
    for (const num2 of array) {
      if (num1 + num2 === target) {
        return (output = [num1, num2]);
      }
    }
  }

  return output;
}

function locateIndices(target, array) {
  return array.reduce((accumulator, current, index, arr) => {
    let output = [...accumulator, current];

    for (const num of accumulator) {
      if (num + current === target) {
        output = [num, current];
        arr.splice(1);
        break;
      }
    }

    return output;
  }, []);
}

Answer №5

const items = [{ name: "apple" }, { name: "banana" }, { name: "orange" }, { name: "grape" }];
const target = "cherry";
let itemSet = new Set(items.flatMap((item) => Object.values(item)));
let itemArray = [...itemSet];

itemArray.forEach((value, index) => {
    let index2 = itemArray.findIndex((v) => v === target - value);
    index2 > -1 && console.log([index, index2]);
})

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

Scrolling automatically within a child element that has a maximum height limit

I am currently developing a console/terminal feature for my website. https://i.stack.imgur.com/AEFNF.jpg My objective is to allow users to input commands and receive output, which might consist of multiple lines of information. When new output is displa ...

Utilizing TypeScript Generics to Dynamically Set Tag Names in React

I am working on a straightforward polymorphic React component that is designed to render only tag names (such as span) and not custom React components (like MyComponent). I believe this can be achieved using JSX.IntrinsicElements. Here is the code snippet ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

Importing 100 .ts files in a dynamic manner

Forgive me for my lack of experience in TypeScript, but I have a query regarding loading multiple .ts files. Imagine I have a directory containing 100 .ts files. Is it appropriate to load all these files using the fs module, as shown below? readdirSync(__ ...

Unable to generate package.json

After attempting to set the execution policies to unrestricted, I was able to resolve my dummy server error, but I encountered an issue creating package.json. The output is displayed below. Please note that I tried both npm init and npm init -y PS C:&bso ...

Issue with updating boolean values in reactive form controls causing functionality to not work as expected

I am currently facing an issue with validating a group of checkboxes. The main problem is that even though the 'this.dataService.minRequired' variable updates in the service, the validation state does not reflect these changes. I initially though ...

Exploring jQuery Mobile: Uncovering the Power of clientX, clientY, and taphold Event

In my current project, I am implementing the taphold event and require the coordinates of the tapped point by the user. However, I have encountered an issue where event.clientX and event.clientY are returning as undefined (you can see the example here: her ...

What could be causing the delay in my scroll event with React Three Fiber?

While using React Three Fiber, I encountered an issue with a react component that generates a sprite which is supposed to remain constant in size regardless of camera zoom. Although the algorithm appears to be functioning correctly (the size does not chang ...

What is the best way to swap out the if else statement with a Ternary operator within a JavaScript function?

Is there a way to replace the if else statement in the function using a Ternary operator in JavaScript? private getProductName(productType: string): string { let productName = 'Product not found'; this.deal.packages.find(p => p.isSele ...

Exploring jQuery AJAX and how to effectively manage various data types

ASP.Net MVC is the framework I am currently using, but this issue can apply to any framework out there. When making an Ajax call to my server, most of the time it returns plain HTML content. However, in case of an error, I want it to return a JSON object ...

I tried to use my Google Maps app, but for some reason, it failed

Here's the code snippet I've been working on: if($_POST){ // get latitude, longitude and formatted address $data_arr = geocode($_POST['address']); // if able to geocode the address if($data_arr){ $latitude = $data_arr[0]; $l ...

X-editable does not verify if the checklist values are checked

Hello everyone, currently I am working on a Laravel project where I have implemented the X-editable library for inline editing functionalities. I am facing an issue with updating a many-to-many relationship table (pivot table) and I am trying to use the X- ...

Retrieving data from a database using a Symfony2 controller in JavaScript

I have been trying to retrieve a list of categories from my database and store it in my JavaScript code for future use. However, I have run into issues with this task as the list appears empty after being returned to JavaScript. Below is the code for my S ...

Ways to retrieve the child number using JavaScript or PHP

Is there a way to retrieve the child number upon clicking? View screenshot For example, when I click on the X button, I want to remove that specific element. However, this action should only apply to item n2. In order to achieve this, I need to determine ...

Establish a predetermined selection for a radio button and its associated checkbox option

I am working on a React material UI group input field that is mapping a dataset. The result consists of one radio button and one checkbox performing the same action. Initially, I attempted to set the state to establish one data item as default. While I fol ...

Mastering the Type Model on Firestore Function to Retrieve Field ValuesUnlock the potential of the Type

When retrieving data from Firestore, I am able to print the entire object using doc.data. However, I am having trouble accessing the specific value of unixtime as it is coming through as undefined. I need help in correctly applying my type model so that I ...

Choose checkboxes based on the checkboxes that were previously selected

My goal is to have a checkbox automatically selected based on the previously selected checkbox. For example, if I select the first checkbox (which has a specific class), then only the checkbox with the same class as the first one should be selected using j ...

Electron: Interactive menu customization

Is there a way in Electron to dynamically enable/disable specific MenuItem in the context menu based on the element that the user right-clicks on? Additionally, I am looking for a method to identify the exact element clicked and pass that information to th ...

Adjusting color with the .on method in Event Listener

What's wrong with this code? html <!DOCTYPE html> <html> <head> <title>Ending Project</title> <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> &l ...

What is the best way to obtain the output produced by a function when a button is clicked

When I click on a button, the desired action is to trigger a function that adds a new property inside an object within a large array of multiple objects. This function then eventually returns a new array. How can I access and utilize this new array? I am ...