Searching for an item's position based on two specific keys

Is there a way to find the index of two keys with specific values in an object?

let myObj = {
"value1":[1,2,3],
"value2":[2,3,4]};

I am trying to locate the index when

myObj.value1==1 && myObj.value2==2
, but I can't figure it out.

edit : perhaps this could work:

if (myObj.value1.indexOf(1) == myObj.value2.indexOf(2)) {
commonIndex = myObj.value1.indexOf(2);}

However, is there a more elegant solution?

Also, how should I handle cases where the value occurs multiple times?

for example :

let myObj = {
"value1":[1,1,1,2,3,4,5],
"value2":[2,3,4,5,6,7,8]}

In this scenario, how can I find the index when value1==1 and value2==3.

Answer №1

This method is recommended for improved efficiency when searching for elements in arrays. Utilizing the indexOf function once instead of multiple times can optimize performance, as it has a time complexity of O(n).

var ind = myObj.value1.indexOf(1);
if (myObj.value2[ind] === 2) {
    commonIndex = ind;
}

Note: If arrays contain duplicate elements and you need to find their indices, consider using this alternative approach:

myObj.value1.forEach(function(val, ind){
    if (val === 1 && myObj.value2[ind] === 2){
        commonIndex = ind;
    }
})

Answer №2

If you want to improve this code, consider the following alternative:

if (myObject.value1.includes(1) !== myObject.value2.includes(2)) {
index = myObject.value1.indexOf(2);}

Answer №3

Here is a handy code snippet you can utilize to retrieve the key based on a specific value within an object:

function findKeyByValue(object, valueToFind) {
  return Object.keys(object).find(key => object[key] === valueToFind);
}

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

Can you explain to me the concept of "face indices" in Three.js and how it functions?

I am attempting to use Three.js to build a unique irregular polyhedron. In order to achieve this, I have decided to utilize the PolyhedronGeometry feature (refer to the documentation). However, I am encountering difficulty in understanding the concept of ...

Accordion content from MUI gets cut off by bookmark bar when expanded

How can I prevent an MUI accordion in an appBar from moving up and hiding behind the browser's bookmark bar when expanded? const useStyles = makeStyles((theme)) => { appBar: { borderBottom: "2px solid #D2D2D2", backgro ...

Switch from using `widthWidth` to `useWidth` in MUI v5 ReactJS

Currently, I am in the process of updating a project that utilizes MUI as the UI Library for my React application. I have started migrating to version 5 today, and one issue I've encountered is related to all functional components wrapped by withWidth ...

What is the best way to retrieve recently inserted data using Sequelize in PostgreSql?

Is there a way to retrieve updated table values after adding a user to the "WOD" table without making an additional query? Currently, when I add a third user to my WOD table, I can only return the first two users because I am unable to access the updated ...

Encountering difficulties with uploading files and images in a Node.js environment

Currently, I am learning node js and express js on Tutorial Point. In the course, I attempted to upload a document but encountered an error that says "Cannot read property 'file' of undefined." Can someone please assist me in resolving this issue ...

Tips for transforming an array of images (from an input field) into a JSON string

After creating an array of images using var a = Array.from(document.getElementById("id").files); I tried to generate a JSON string of that array using var b = JSON.stringify(a); However, all I get is an empty array. It seems like this issue is common w ...

The Angular modal feature is specifically designed to function exclusively within the index.html

Success! My angular modal is now functioning properly. https://i.sstatic.net/CUHpL.png One thing to note is that the modal script must be placed within my index.html file for it to work: <script type="text/ng-template" id="myModalContent.html"> ...

Transitioning from jQuery to Prototype

After switching from a jQuery background to Prototype, I am curious if there is a chart available that shows the equivalent prototype methods for specific jQuery methods? To be more specific, I am searching for the equivalent of $('#my-id').prep ...

"Uncovering the parent element with jQuery: A step-by-step guide

I need help increasing the font size of a parent element without affecting the entire body's font size. How can I achieve this? For example, with the id="vs-1", I want to increase the font size of the grandparent li text here which is "1940". $("li ...

Querying an update on a MongoDB subarray

Updating a specific field within an array of objects nested inside another array in MongoDB. The particular field I am focusing on in my MongoDB schema is: otherFields: values, tasks: [ { _id: mongodb.objectID(), title: string, items:[{ _id: mo ...

"Enhancing event handling: Using addEventListener natively with selectors similar to .on()

Has anyone figured out how to replicate jQuery's .on() method in vanilla JavaScript? The native addEventListener function doesn't seem to have the capability to filter based on child/selector elements, and delving into event bubbling and capturin ...

What is the best way to display the text of a button once it has been clicked?

Trying to implement a fade-in effect on text when clicking a button. Any assistance would be greatly appreciated! $(".btnClick").click(function(event) { var x = $(this).text(); if (x == "PowerApps") { $(this).parent(".show-details").find('. ...

Acquiring POST parameters within Laravel's Controller from JavaScript or Vue transmission

I am trying to send Form data from a Vue component to a Laravel API using the POST method. Although Laravel is returning a successful response, I am encountering difficulty in handling the POST data within the Laravel controller. Below is the code for th ...

Navigation bar not visible when scrolling

I recently purchased the Mix Responsive App Landing Page theme from Theme Forest and have had success customizing it, except for when I started removing unnecessary sections. Ever since the removal, the header does not function as intended - it should be h ...

When utilizing backend Node.js with MongoDB, the patch request is unable to successfully update date type values

Using node.js, I have created the backend and integrated MongoDB for data persistence. However, I am facing an issue where I am unable to update the field of date type when making a patch request. Below is the code snippet for handling patch requests in t ...

Nested within an it block are Protractor Jasmine describe blocks

Initially, the code provided below appears to be functioning properly. However, I have not come across anyone using this method before, leading me to question its validity and potential unforeseen drawbacks. The scenario involves writing an end-to-end tes ...

Why is the value returned by getBoundingClientRect 190 when the y attribute is set to 200 in SVG?

When placing textBox1 at a y-position of 200, getBoundingClientRect is returning a value of 190. What could be causing this discrepancy? For more details and code snippets, please refer to the following link: https://codepen.io/anon/pen/REKayR?editors=101 ...

Using Mocks in a NestJS Program to Enhance Contract Testing

Challenge I am currently exploring ways to launch a NestJS application with mocked providers. This is essential for conducting provider contract tests, as a service needs to be initiated in isolation. When using the Pact library for testing the provider, ...

Passing the value of the selected calendar date to the controller

How can I pass the value generated by this calendar_date_select to the controller? Any suggestions on how to modify the onchange code? <%= calendar_date_select_tag "meeting_date_1", @time, :embedded => true, :time => true, :minut ...

Looking for jQuery bbq... is the grill fired up yet?

In my exploration of the jQuery bbq plugin, I noticed that there is no reference to document.hash in the code. I believe that the function for retrieving the hash is located at line 1094: function get_fragment( url ) { url = url || location.href; ...