Home > OS >  How to find the lastIndexOf if Array.includes returns true?
How to find the lastIndexOf if Array.includes returns true?

Time:08-13

I have two arrays

let arr1 = ['Red, 'Blue', 'Black', 'Gold', 'Silver', 'Black']

let arr2 = ['Black', 'White', 'Green']

I am writing below function to check if arr1 includes arr2 value

function findCommonElements(arr1, arr2) { 
return arr1.some(item => arr2.includes(item))
}

my function is working fine and it returns true since arr1 includes Black, but I want to know the lastIndexOf position of matched value if findCommonElements returns true

CodePudding user response:

Use find and includes (note: find will short-circuit the loop if it finds a match - it won't progress any further so all you'll be guaranteed is one match or no match), and then, if found return the last index of found.

const arr1 = ['Red', 'Blue', 'Black', 'Gold', 'Silver', 'Black'];
const arr2 = ['Black', 'White', 'Green'];

function findIndexOfCommon(arr1, arr2) { 
  const found = arr1.find(el => arr2.includes(el));
  if (found) return arr1.lastIndexOf(found);
  return undefined;
}

const index = findIndexOfCommon(arr1, arr2);

if (index) arr1[index] = 'White';

console.log(arr1);

CodePudding user response:

I am not sure exactly what you are trying to do but this function will return 5 (the index of 'Black' in arr1)

function findCommonElements(arr1, arr2) {
  return arr1.reduce((a, item, i) =>  arr2.includes(item) ? i : a  , -1)
}

CodePudding user response:

let ar1 = ['Red', 'Blue', 'Black', 'Gold', 'Silver', 'Black'];
let ar2 = ['Black', 'White', 'Green'];

function findMatch(array_1_small, array2_large) { //first parameter must be smallest array
var ary = new Array();
for(i = 0;i < array2_large.length; i  )
{
  for(z = 0; z < array_1_small.length; z  )
  {
    if(array2_large[i] == array_1_small[z])
    {
      ary.push(i);
    }
  }

}
return ary;}

findMatch(ar2, ar1) //first parameter must be smallest array

findMatch will return [2, 5] from this array you can get last matched index

  • Related