Home > Enterprise >  Search bidimensiona array X element in another bideimensional array Y - Javascript
Search bidimensiona array X element in another bideimensional array Y - Javascript

Time:11-15

I have 2 arrays X and Y:

X= [['a', 'b', 'c'], ['d', 'e', 'f']]

Y= [['a', 'x', 'c'], ['y', 'z', 'c']]

In reality X has hundreds of elements.

How can I know the INDEXES of X elements that have a and c in the 1st and 3rd position which are respectively Y[0][0] and Y[0][2] ?

I have tried combining methods findIndex(), toString() and indexOf() but I am not getting the result I expect.

It still gives results even if it finds SALE while I search SALES.

CodePudding user response:

You can search like this. Here are sample code.

Y = [['a', 'x', 'c'], ['y', 'z', 'c']]
index = Y.toString().indexOf('y') / 2;
console.log( Math.floor(index / 3), index % 3)
// Another Method.
console.log(
  Math.floor(Y.toString().split(',').indexOf('y') / 3 ), 
  Y.toString().split(',').indexOf('y') % 3
)

CodePudding user response:

Check this question for how to search array in array: javascript-search-array-of-arrays

basically you need to iterate through both arrays and check value by value if the element is in the second array (The code below it's just an example, it's not very optimal but you can start something from here)

const X = [
  ['a', 'b', 'c'],
  ['d', 'z', 'f']
]
const Y = [
  ['a', 'x', 'c'],
  ['y', 'z', 'c']
]

function indexOfArray(val, array) {
  var hash = {};
  for (var i = 0; i < array.length; i  ) {
    hash[array[i]] = i;
  }
  return (hash.hasOwnProperty(val)) ? hash[val] : -1;
};

function findIndexInNestedArray(array1, array2) {
  array1.filter((xItem) => {
    console.log('X array '   xItem)
    xItem.some((xValue) => {
      array2.filter((yItem) => {


        if (indexOfArray(xValue, yItem) !== -1)
          // you can access everything from here
          console.log('index of ', xValue, ' in', yItem, ' : ', indexOfArray(xValue, yItem))
          
          //return result as an object or whatever type you need
      })
    })
  });
}


findIndexInNestedArray(X, Y)
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

This is the code I wrote:

X= [['a', 'b', 'c'], ['d', 'e', 'f']]

Y= [['a', 'x', 'c'], ['y', 'z', 'c']]

var index = X.findIndex(function(item) {return item.toString().indexOf(Y[0][0]) != -1 && Y.toString().indexOf(X[0][2]) != -1});

if (index > -1){ 'do something }

else {'do something else'}

  • Related