Searching for indices in a multidimensional array using JavaScript

Dealing with a JavaScript array can be so challenging, especially when it comes to searching for an index. In my case, I have an array that contains objects, and each object has an array as one of its values.

This is the snippet of my source code:

rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];

I attempted the following:

var v = {cell:["array1","array2"]};
rows.indexOf(v)

In addition, there is a radio button:

<input type="radio" name='array' value="array1, array2">

Here's how jQuery plays into this scenario:

var i = $("input:checked").val().split(',');
rows.indexOf(i)

Unfortunately, the result of the index turns out to be -1.

Answer №1

Give this a shot. This method takes a functional approach by iterating through each row index and returning true if a match is found.

var rows = [{"id":"id0","cell":["array1","array2"]},{"id":"id1","cell":["array3","array4"]}];
var index = rows.findIndex(function(i) {
  return JSON.stringify(i.cell) == JSON.stringify(["array1","array2"])
});
console.log(index);

The expected output is 0. We convert both objects into JSON strings to handle how JavaScript compares object equality. More information on this topic can be found here.

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

Send an array from PHP to jQuery using AJAX, then send the array back from jQuery to PHP

I am facing a dilemma where I am passing an array from PHP to jQuery AJAX using `json_encode` and storing it in an empty array declared in the jQuery script as `var myarr = []`. Later in the same script, I am sending the same array `myarr` back to the PHP ...

What regular expression should be used to meet the following requirement in JavaScript?

Criteria: Find words that begin with 'a' and end with 'b', with a digit in the middle, but are not on lines starting with '#' Given string: a1b a2b a3b #a4b a5b a6b a7b a8b a9b Expected output: a1b a2b a3b a7b a8b ...

What steps can I take to trigger a 404 error instead of a cast error?

My route is defined as /mysafe/idofthemodel. When the idofthemodel is not found, it throws a cast error Cast to ObjectId failed for value "something" (type string) at path "_id" for model "modelname". Instead of this error, I ...

import jQuery into a JavaScript file

I'm currently working on a Chrome extension that relies on background.js to perform basic tasks. I need to include jquery.js in my background.js file so that I can utilize its ajax function, but I'm unsure of how to achieve this. Is it even possi ...

Calculate the total value for each key in PHP arrays

Here are the arrays that contain totals for a monthly report: Array ( [name] => Innovativo [Total] => 98910.44 [Pedidos] => 89 [Descuento] => 448.54 [Clientes] => 11 [Pliegos] => 1504.100 ) Array ( [name] => Visionario [Tot ...

Issue with the scope of Bootstrap Accordion

Observing that the event triggers on a single Bootstrap accordion can affect all other accordions on the same page, I am wondering if there is a way to isolate this behavior without altering the markup or using $(this). Any suggestions? Check out this exam ...

Alter attribute with an impact

I am looking for a solution to switch the image source using attr, while also incorporating a fade effect in the process. I have attempted to implement one of the suggestions from another post, but it is not producing the desired outcome. Current Appearan ...

Sometimes, Node.js struggles to retrieve values from my configuration file

I'm currently utilizing node.js on the server side with a RESTful service setup as follows; app.get('/getAndroidVersion', function(req,res){res.json({version: config.androidVerion});}); This service is expected to return the version value ...

Assistance is required to navigate my character within the canvas

Having trouble getting the image to move in the canvas. Have tried multiple methods with no success. Please assist! var canvas = document.getElementById("mainCanvas"); canvas.width = document.body.clientWidth; canvas.height = document.body.clientHeight; ...

Traverse through a string and populate a C++ array

Currently, I'm tackling a coding problem that involves iterating over a string. However, in this case, the string represents an integer, and I need to fill an array with each "digit" of the string. For example, if the string is "350", then the resulti ...

Tips for setting up a range slider for decimal numbers

I have implemented the following code for a range slider. It works perfectly fine for integer values like 1 and 100, but I am facing issues when trying to use decimal values. I attempted to substitute 1 with 0.1 but it did not yield the desired result. ...

How to display (fade in a portion of an image) using .SVG

I have the following code in my DOM: <div class="icon-animated"><img src="icon_non_active.svg" id="icon_non_active"></div> There are two icons (.svg) available: icon_non_active & icon_active Can I animate the transformation from i ...

Leveraging EJS for embedding Google Maps API on a website

Currently, I am utilizing EJS to display the Google Maps API on a particular webpage. <!DOCTYPE html> <html> <head> <title></title> </head> <body> <div id="map"></div> <script> var ...

What is the correct way to incorporate a for loop within a script tag in EJS?

When attempting to create a chart using chart.js, I encountered an issue. In order to retrieve my data, I attempted to use ejs tags. For example, within the ejs input HTML below, everything worked smoothly. <p>date: <%= today %></p> ...

Transferring an array from PHP to Javascript using GET method

Can someone help me figure out how to pass an array to Javascript after it sends a GET request to PHP? I've got the data sending and retrieving down pat, but now I'm stuck on how to send the data back as an array. Here's what I have so far: ...

incorporating event handlers to references retrieved from bespoke hooks

I have designed a simple custom hook in my React application to manage the onChange events of a specific input element. const useInput = () => { const ref = useRef(null); const handleChange = () => { console.log("Input has been ...

Can we safely save a value in session storage directly from the main.js file in Vue?

Throughout the user session managed by Vuex, I have a session storage value set to false that needs to be monitored. Setting up this value directly from the main.js file looks like this: import { createApp } from 'vue'; import App from './Ap ...

Using the ternary operator to insert elements from one JavaScript array into another array

In my React form, I am dealing with an array of objects that represent different fields. Depending on a boolean state, I need to dynamically change the sequence of fields displayed. While I have no trouble inserting a single object into the array, I am s ...

Utilizing regular expressions for querying MongoDB

Attempting to retrieve data from MongoDB by querying for a specific field name using regular expressions. For example, if the constant name is set as 'st', the expected result would be 'steven', 'stephanie', and 'stella&a ...

Showing information from a database while incorporating line breaks with the help of nl2br

Having trouble with the previous question, so I'll provide more detail here. Below is my index.php file where I explain the method used to save data to a database. <html> <head> <script> function updategroup() { var update_c ...