Discover the position within a two-dimensional array

Suppose I have an array that contains objects, and each object has its own id property. In this case, I can find the index by writing:

data.findIndex(x=>x.id === newData.id);

Now, if data is an array of arrays of objects, how can I efficiently get two indexes for this data structure? Meaning that data.findIndex would return both i and j conveniently.

Answer №1

To check for specific values in an array, you can utilize Array.includes within the findIndex method.

var data = [
  [1,2,3],
  [4,5,6],
  [7,8,9]
]
var searchParam = 8;
var index = data.findIndex(x=>x.includes(searchParam))
console.log(index)

If dealing with arrays of nested objects, recursion comes in handy to search through them.

var data = [
  [{id: 1},{id: 2},{id: 3}],
  [{id: 4},{id: 5},{id: 6}],
  [{id: 7},{id: 8},{id: 9}]
]
var searchValue = 8;
var index = data.findIndex(x=>{
  return searchInObject(x, searchValue);
})

function searchInObject(obj, searchValue){
  var _s = JSON.stringify(obj);
  if(_s.indexOf(searchValue)>-1){
     if(Array.isArray(obj)){
       return obj.some(function(o){
         if(searchInObject(o, searchValue)) return true;
       });
     }
    else if(typeof(obj) === 'object'){
      for(var k in obj){
        if(searchInObject(obj[k], searchValue)) return true;
      }
    }
    else{
      if(obj === searchValue) return true;
    }
  }
}
console.log(index)

Answer №2

Here is a unique approach to creating a recursive find index function using Array.prototype.reduce() that can navigate through multiple levels of nesting:

const recursiveFindIndex = (data, id) =>
  data.reduce((indexes, item, index) => {
    let subIndex;

    Array.isArray(item) && (subIndex = recursiveFindIndex(item, id));

    if (subIndex && subIndex.length) {
      return indexes.concat([index], subIndex);
    }

    item.id === id && (indexes.push(index));

    return indexes;
  }, []);

const data = [
  { id: 0 },
  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
  [{ id: 6 }, { id: 7 }, { id: 8 }, { id: 9 }, [
    { id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }, { id: 14 }]
  ]
];

console.log('id: 3', recursiveFindIndex(data, 0));
console.log('id: 3', recursiveFindIndex(data, 3));
console.log('id: 6', recursiveFindIndex(data, 8));
console.log('id: 12', recursiveFindIndex(data, 12));
console.log('id: 3', recursiveFindIndex(data, 20));

Additionally, a more efficient version is presented here which terminates the search once a match is found by utilizing a for loop:

const recursiveFindIndex = (arr, predicate) => {
  let subIndex;
  
  for(let i = 0; i < arr.length; i++) {
    if(Array.isArray(arr[i])) {
      subIndex = recursiveFindIndex(arr[i], predicate);
      
      if(subIndex !== -1) {
        return [i].concat(subIndex);
      }
    } else if(predicate(arr[i])) {
      return [i];
    }
  }

  return -1;
};

const data = [
  { id: 0 },
  [{ id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }, { id: 5 }],
  [{ id: 6 }, { id: 7 }, { id: 8 }, { id: 9 }, [
    { id: 10 }, { id: 11 }, { id: 12 }, { id: 13 }, { id: 14 }]
  ]
];

console.log('id: 0', recursiveFindIndex(data, (item) => item.id === 0));
console.log('id: 3', recursiveFindIndex(data, (item) => item.id === 3));
console.log('id: 6', recursiveFindIndex(data, (item) => item.id === 8));
console.log('id: 12', recursiveFindIndex(data, (item) => item.id === 12));
console.log('id: 20', recursiveFindIndex(data, (item) => item.id === 20));

Answer №3

Is this the kind of approach you had in mind?

While it may not be the most sleek solution, it does get the job done:

const updatedData = { id: 2 };
const dataSet = [[{id: 5}, {id: 2}], [{id: 7}, {id: 8}]];

dataSet.reduce((result, array, index) => {
  let position = array.findIndex(item => item.id === updatedData.id);

  if (~position) {
    return [index, position];
  }

  return result;
}, [-1, -1]);

Answer №4

Here is an example utilizing the reduce method:

const items = [
    [{ id: 1 }, { id: 4 }],
    [{ id: 2}, { id: 3 }]
]

const searchId = (items, id) => 
  items.reduce((prev, curr, index) => {
    let result = curr.findIndex(x => x.id === id);
    if(result > -1){
        prev = { index, result }
    }
    return prev;
  }, { index: -1, result: -1 });

Check out this demo on JSFiddle

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

When using Node.js with Mongoose, you will receive a single object value instead of multiple values in an array

data=[{ locId: '332wn', locadetails: [ { loc: 'ny', status: true }, { loc: 'ca', status: null ...

How can I convert a MongoDB document into a DTO in NestJS?

I'm currently working with a data layer that interacts with a MongoDB database. My goal is to only handle MongoDB documents in this layer without exposing the implementation details to my services. My current approach involves the following code: // ...

Having difficulty with loading JSON data into jqGrid

Explaining my jqGrid definition: . . . datatype: 'json', //Setting the data type to JSON url:'<%=request.getContextPath()%>/servlet/AjaxManager?mode=9999&beginindex=0&totallimit=10&colname=policyname&sorttype=asc&apos ...

Is there a way to efficiently compare multiple arrays in Typescript and Angular?

I am faced with a scenario where I have 4 separate arrays and need to identify if any item appears in more than two of the arrays. If this is the case, I must delete the duplicate items from all arrays except one based on a specific property. let arrayA = ...

Displaying array elements on a webpage using JavaScript in HTML

Looking to display multiple blocks in HTML using a JavaScript array. The array contains names such as: var name=['amit','mayank','jatin'];. I need to repeat a certain portion of code in order to show the elements of the array, ...

Issue with Yup and Formik not validating checkboxes as expected

I'm struggling to figure out why the validation isn't functioning as expected: export default function Check() { const label = { inputProps: { "aria-label": "termsOfService" } }; const formSchema = yup.object().shape({ ...

Display a message if the local storage is empty

Recently, I came across a javascript code snippet that is designed to save birthday data in local storage and then display the data within a div element. The current functionality only shows nothing if the storage is empty. However, I require it to display ...

Disable the enter key from closing the alert box

Is there a way to ensure that a user must manually close a JavaScript alert, preventing them from simply closing it by pressing enter? (It may sound suspicious, but in the application users frequently press enter and I need to make sure they don't ov ...

Obtain the ID of element 1 by clicking on element 2 using JQuery

In the world of javascript/jquery, When button1 is clicked, we can get its id like this: var button1id = $(this).attr("id"); If button2 is clicked, how do we retrieve button1's id? This brings us to the question: How does button2 access the i ...

Why am I encountering issues accessing a child property in TypeScript?

Here is some TypeScript code that I am working with: export interface SelectQuery_thing { __typename: "ThingQueryPayload"; content: (SelectQuery_thing_content | null)[]; pageInfo: SelectQuery_thing_pageInfo; } export interface SelectQuery_thing_con ...

Leveraging jQuery to detect an AJAX load that does not involve the use of jQuery's AJAX method

Hi all, I have a challenging issue that I'm struggling with in terms of jQuery/JavaScript. I am fetching data through standard AJAX without using any frameworks like jQuery. Now, the dilemma is that once the page has loaded, I need to implement a jQu ...

Remove child elements in Jquery that do not match the specific numbers saved in the array

I've got this array: var numbersArray = [1, 2, 4, 5] and also an unordered list in HTML <ul> <li> item 1 </li> <li> item 2 </li> <li> item 3 </li> <li> item 4 </li> <li> item 5 ...

How can we modify specific values of an object using Lodash and return the updated object?

const fruits = { apple: 2, orange: 3, grape: 4, banana: 5 } My aim is to adjust the values of certain fruits while being able to reference their current values. For example: const premiumFrutis = _.doSomething(fruits, apple + 2, banana + ...

Unlocking the potential: Clicking on all ng-if elements with matching text using Chrome console

I am currently trying to determine how to automatically click on all elements that have a specific state. The page appears to be built using Angular, although I am unsure of the exact version being used. My approach involves using the console in Chrome t ...

Inserting data into a Textbox by clicking on a Div

I'm currently working on creating a wallpaper changer for my website. Right now, I'm looking to input the URL of a wallpaper into a text box when the corresponding DIV option in a CSS menu is clicked. Below is the JQuery I am using: $("div.bg8 ...

Acquire data from an HTML Element

I was provided with the following div that was already created for me: <div data-sudo-slider='{"slideCount":1, "moveCount":1, "customLink":"#slider-nav a", "continuous":true, "updateBefore":false, "effect":"sliceRevealDown", "auto":true, "speed":1 ...

Troubles with proper functionality of antd's DatePicker.RangePicker within a React Function Component

I am currently utilizing React and the antd library, attempting to incorporate the DatePicker.RangePicker into my project. Initially, when I directly embed the RangePicker within the component, everything works smoothly. However, for better code organizat ...

When the value of a Formcontrol is changed using valueAccessor.writeValue(), it remains unchanged

Encountering a similar issue as seen in this stack overflow post, but the solution provided isn't resolving the issue. Perhaps you can offer assistance on that thread. In my scenario, I have created a directive for formatting phone numbers: import { ...

What causes the transformation of a MATLAB 2D character array into a Python 1D array?

When using Scipy to import a MATLAB 2D matrix into Python, I encountered an issue where the matrix, which is initially a 32x40 Char matrix in MATLAB, transforms into a (32,) numpy array in Python. This numpy array treats each character as a separate row of ...

I would like to inquire about the process of accessing profile information on a website through the LinkedIn API

Do you know how I can use the latest LinkedIn JavaScript API with OAuth 2.0 to retrieve my own profile details for a website? The goal is to automatically update the website using my linked profile information. I have attempted the following: api_key: ...