6 kyu

IndexOf Array in Array

1,158 of 1,240danmarcus

Description:

JavaScript's indexOf does not work with arrays as input. This is because [1,2] === [1,2] will return false in JavaScript. Many other languages have similar quirks.

However, sometimes it is useful to search for an Array. 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.

See some examples:

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

You will be required to validate the inputs on the following criteria:

  • each element of the array to be searched should be an array;
  • each sub-array in the two-dimensional array should be of length two; and
  • query should be an array of length two.

If the inputs are not valid you should throw an Error.

See some examples:

var arrayToSearch = [[1,2],[3,4],[5,6],[7,8,9]]; // => throw Error
arrayToSearch = [1,2,3,4,5,6]; // => throw Error
arrayToSearch = [[1,2],[3,4],[5,6]]; // => valid input
var query = [1,2]; // => valid input
query = 5; // => throw Error
query = [9,2,1]; // => throw Error
var arrayToSearch = new object[] { new object[] { 1,2 }, new object[] { 3,4 }, new object[] { 5,6 }, new object[] { 7,8,9 } }; // => throw Exception
arrayToSearch = new object[] { 1,2,3,4,5,6 }; // => throw Exception
arrayToSearch = new object[] { new object[] { 1,2 }, new object[] { 3,4 }, new object[] { 5,6 } }; // => valid input
var query = new object[] { 1,2 }; // => valid input
query = new object[] { 9,2,1 }; // => throw Exception
Arrays
Algorithms

More By Author:

Check out these other kata created by danmarcus

Stats:

CreatedJul 11, 2016
PublishedJul 11, 2016
Warriors Trained2809
Total Skips70
Total Code Submissions13269
Total Times Completed1240
JavaScript Completions1158
C# Completions95
Total Stars60
% of votes with a positive feedback rating88% of 252
Total "Very Satisfied" Votes203
Total "Somewhat Satisfied" Votes35
Total "Not Satisfied" Votes14
Total Rank Assessments10
Average Assessed Rank
6 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
8 kyu
Ad
Contributors
  • danmarcus Avatar
  • user5036852 Avatar
  • hobovsky Avatar
  • XoRMiAS Avatar
Ad