Locate the index position of an element in one array based on a corresponding element in a

I am seeking a way to determine the index and group that an item belongs to within a parent json group. Is there a method for achieving this? I am willing to modify the json format if necessary.

I made an attempt using JSON.stringify(), but it seems to be returning an incorrect index.

let Content = {
    group1: [
      [{content:"hello"},{content:"world"}],
      [{content:"hello1"},{content:"world"}],
      [{content:"hello2"},{content:"world"}],
      [{content:"hello3"},{content:"world"}],
      [{content:"hello4"},{content:"world"}],
      [{content:"hello5"},{content:"world"}],
    ],
    group2: [
      [{content:"hello10"},{content:"world"}],
      [{content:"hello11"},{content:"world"}],
      [{content:"hello12"},{content:"world"}],
      [{content:"hello13"},{content:"world"}],
      [{content:"hello14"},{content:"world"}],
      [{content:"hello15"},{content:"world"}],
    ],
  };
//   let currentItem = {type:'group2',index:5};
//   let currentItemContent = Content[currentItem.type][currentItem.index];
let obj = [{content:"hello15"},{content:"world"}];
let newIndex =  Content["group1"].indexOf(obj); 
let type = "group1"; 
if(newIndex < 0)
{
  type="group2"
  console.log(Content["group2"]);
  newIndex = Content["group2"].indexOf(obj); 
}
console.log({"type":type,"index":newIndex});

expected: {type:'group2',index:5}

Answer №1

Iterate through the Data object using a for...in loop. Search for the specified array within each group using findIndex. As the objects in the array are ordered, comparing their JSON string representation with JSON.stringify is sufficient.

let Data={group1:[[{content:"hello"},{content:"world"}],[{content:"hello1"},{content:"world"}],[{content:"hello2"},{content:"world"}],[{content:"hello3"},{content:"world"}],[{content:"hello4"},{content:"world"}],[{content:"hello5"},{content:"world"}]],group2:[[{content:"hello10"},{content:"world"}],[{content:"hello11"},{content:"world"}],[{content:"hello12"},{content:"world"}],[{content:"hello13"},{content:"world"}],[{content:"hello14"},{content:"world"}],[{content:"hello15"},{content:"world"}]]}

function searchArray(input, query) {
  for (const key in input) {
    const group = input[key];
    const idx = group.findIndex(arr => JSON.stringify(arr) === JSON.stringify(query));
    
    if (idx != -1)
      return { key, idx }
  }
  return null
}

console.log(find(Data, [{content:"hello15"},{content:"world"}]))
console.log(find(Data, [{content:"hello"},{content:"world"}]))

Answer №2

To achieve this, you have the option of utilizing Array.find along with Object.keys and Array.some. It is important to note that when comparing arrays using JSON.stringify, the order of keys must be consistent in order for accurate comparisons:

[{content:"world"},{content:"hello"}] vs [{content:"hello"},{content:"world"}]

This comparison will not yield the expected result due to the different key orders resulting in mismatched strings.

let Content = { group1: [ [{content:"hello"},{content:"world"}], [{content:"hello1"},{content:"world"}], [{content:"hello2"},{content:"world"}], [{content:"hello3"},{content:"world"}], [{content:"hello4"},{content:"world"}], [{content:"hello5"},{content:"world"}], ], group2: [ [{content:"hello10"},{content:"world"}], [{content:"hello11"},{content:"world"}], [{content:"hello12"},{content:"world"}], [{content:"hello13"},{content:"world"}], [{content:"hello14"},{content:"world"}], [{content:"hello15"},{content:"world"}], ], };
    
let findArray = (data, obj) => {
  let index, group = Object.keys(data).find((k,i) => {
    index = i
    return data[k].some(x => JSON.stringify(x) === JSON.stringify(obj))
  })
  return { index, group }
}

console.log(findArray(Content, [{content:"hello"},{content:"world"}]))
console.log(findArray(Content, [{content:"hello10"},{content:"world"}]))

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

Transfer an Array of Objects containing images to a POST API using Angular

Looking to send an array of objects (including images) to a POST API using Angular and Express on the backend. Here's the array of objects I have: [{uid: "", image: File, description: "store", price: "800"} {uid: "f ...

Generating JSON data from a loop with refined outcomes

My goal is to iterate through JSON data and extract "time", "blocks" information, while filtering the "amounts" based on a specific variable named _miner. So far, I've successfully retrieved the name, time, and blocks data, but I'm struggling wi ...

What is the best way to retrieve all objects from this data model?

I am looking to collect all the Model Objects from the data structure provided below. const PRODUCTS = [ { brand: 'Audi', allSeries: { serie: 'A3', allModels: [ { model: ' ...

Nested mapping of objects in a mapped object

I'm attempting to iterate through an array within another array that has already been iterated My objective is to display the userName and products each user has. To achieve this, I first map the main data array to show the userName of each object. ...

Ways to pass a message from index.html to a Vue.js 3 instance

Picture this scenario: You have a Vue index.html file that also loads a custom script: <!DOCTYPE html> <html lang="en"> <head> ... ... <script type="text/javascript"> languagePluginLoader.then(fun ...

Deleting the clone <div> while ensuring the main <div> is kept clear of any remaining data

Initially: https://i.sstatic.net/SLG7O.png After adding a new row and then removing it. https://i.sstatic.net/FegjK.png Why is this happening? When I set val(""), the textbox should have no value. What mistake did I make in my code? Please assist. Her ...

Check for length validation including spaces in JavaScript

My code includes a functionality that calculates the length of characters in a text area using both JSP and JavaScript: <textarea class="textAreaLarge" id="citation" rows="20" cols="180" name="citation" ...

How can I prevent an HTML element from losing focus?

Currently, I am developing an online editor that requires accurate character inputs. To achieve this, I have implemented the jQuery.onKeyPress event on a textarea element. This approach was chosen because obtaining character inputs from the body directly p ...

The issue with ajax in CodeIgniter is that it keeps displaying a false message, even though the value is present

Trying to validate the existence of a value in the CodeIgniter website's database using AJAX. Below is the code snippet: <input id="username" name="pincode" type="text" class="form-control" placeholder="Enter Pincode"> <input id="prodid" n ...

AngularJS single page applications experiencing issues with loading scripts and stylesheets upon page reload

Homepage Setup : <ng-view></ng-view> Angular Routing Configuration : when('/', { url: '/', templateUrl: 'site/home', controller: 'indexController' }). when(&apos ...

Increase the value of a property within an array of objects based on certain conditions

My task involves incrementing the rank value by one until the name property changes. I am utilizing the page and rank properties to track when this change occurs. In addition, I want to increment it once whenever the type is not equal to none, and then re ...

The array containing numbers or undefined values cannot be assigned to an array containing only numbers

Currently facing an issue with TypeScript and types. I have an array of IDs obtained from checkboxes, which may also be empty. An example of values returned from the submit() function: const responseFromSubmit = { 1: { id: "1", value: "true" }, 2: ...

NGRX Store: Unable to modify the immutable property '18' of the object '[object Array]'

While attempting to set up an ngrx store, I encountered 7 errors. Error Messages: TypeError: Cannot assign to read only property '18' of object '[object Array]' | TypeError: Cannot assign to read only property 'incompleteFirstPass ...

Is there a radio button that can dynamically update and modify the current view?

Although I don't consider my issue to be overly complex, as a newcomer I am struggling to find a straightforward solution. The form I have collects various items and on the output page generates a table based on this data. For instance, one question ...

Customizing font size in React with Material UI: A comprehensive guide on adjusting the font size of the Select component

I'm currently working on a web application that utilizes React along with Material UI. My goal is to adjust the font size of the Select component. I've attempted to achieve this by utilizing the MenuProps property, as shown in the following code ...

The issue arises when trying to use data provided by a service, resulting in an "undefined

Looking to create a handler that generates an array of categories based on the presence of "categories" for a specific "resource". However, encountering an error with the last method. ERROR TypeError: "this.allProjectResources is undefined" import { Res ...

Role="presentation" containing a <form> element within

<nav> <ul class="nav nav-pills pull-right"> <li role="presentation"> <form action="/logout" method="POST" id="logout-form"> <a href="#" onClick="document.getElementById('logout-form&ap ...

FlexSlider in WordPress is failing to display captions

Before pointing out any similar questions, please note that the answer from those sources does not apply to my specific code. I am trying to achieve this through a function as outlined here But I am struggling to figure out how to add captions only if th ...

A Step-by-Step Guide to Mocking a jQuery Function Using Jasmine in an Angular Directive Specification

When working with an angular directive, I am currently using $(element).fdatepicker(). How can I mock or stub this function in a jasmine test for the directive? If I don't stub it, I encounter the following error: TypeError: 'undefined' is ...

Utilize Mongoose to seamlessly integrate online shopping cart items into MongoDB

I am facing an issue while trying to insert a shopping cart of items in the form of a JSON object into a MongoDB collection using a mongoose schema. Although the customer's ID is successfully stored (extracted from the User DB), unfortunately, the ca ...