Home > database >  CodeWars Javascript challenge: IndexOf Array in Array
CodeWars Javascript challenge: IndexOf Array in Array

Time:03-14

I'm trying to complete this exercise from codewars. The instructions say: " Write a function that looks for an array within a two-dimensional array and returns the index of the first matching element. If there is no match, your function should return -1"

Exemples:

var arrayToSearch = [[1,2],[3,4],[5,6]];
var query = [1,2]; // => 0
query = [5,6]; // => 2
query = [9,2]; // => -1

This is my solution, but it still fails.

var searchArray = function (arrayToSearch, query) {
  for(i = 0; i < arrayToSearch.length; i  ) {
    for (j = 0; j < arrayToSearch[i]; j  ) {
      if (arrayToSearch[i][j] === query) {
      return i;
    }
   }
  }
 return -1;
}

I'm not sure what I'm doing wrong, but I think the problem is in the if statement, but I don't know what it is.

CodePudding user response:

Issue in logic.

Your second if condition j < arrayToSearch[i] will always returns false, because you are comparing a number j against an array arrayToSearch[i]. In this case the number j will be compared agaist the first elementin the array arrayToSearch, which makes the function always returns -1.

Corrected Code

var arrayToSearch = [[1, 2], [3, 4], [5, 6]];
var query = [1, 2]; // => 0
// query = [5, 6]; // => 2
// query = [9, 2]; // => -1

var searchArray = function (arrayToSearch, query) {
  for (i = 0; i < arrayToSearch.length; i  ) {
    let isEqual = true;
    for (j = 0; j < arrayToSearch[i].length; j  ) {
      isEqual = isEqual && (arrayToSearch[i][j] === query[j])
    }
    if (isEqual) {
      return i;
    }
  }
  return -1;
}

console.log(searchArray(arrayToSearch, query));

CodePudding user response:

this simple code will work.

var arrayToSearch = [[1,2],[3,4],[5,6]];
var query = [1,2];
    var searchArray = function (arrayToSearch, query) {
        for (var i = 0; i < arrayToSearch.length; i  ) {
            if (arrayToSearch[i][0] == query[0] && arrayToSearch[i][1] == query[1]) {
                return true; 
            }
        }
        return -1;
    }

CodePudding user response:

One-liner if you don't mind:

const arrayToSearch = [[1,2],[3,4],[5,6]];
const query1 = [1,2];
const query2 = [3,4];
const query3 = [5,6];
const query4 = [9,2];

const searchArray = (arr, query) => arr.map(e => e.toString()).indexOf(query.toString());
  
console.log(`[${query1}]:`, searchArray(arrayToSearch, query1));
console.log(`[${query2}]:`, searchArray(arrayToSearch, query2));
console.log(`[${query3}]:`, searchArray(arrayToSearch, query3));
console.log(`[${query4}]:`, searchArray(arrayToSearch, query4));
.as-console-wrapper{min-height: 100%!important; top: 0}

  • Related