Skip to content Skip to sidebar Skip to footer

Get Coordinates Of An Element In Multidimentional Array In Javascript

I want to where is placed an element in an multidimentional array like that : Is it possible ?

Solution 1:

Run a simple for loop and check if the character exists in the inner array using indexOf. return immediately once a match is found

var letterVariations = [
  [' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', ';'],
  ['Â', 'â', 'F', 'f', 'G', 'g', 'H', 'h', 'Ê', 'ê', ':'],
  ['À', 'à', 'I', 'i', 'J', 'j', 'K', 'k', 'È', 'è', '.'],
  ['L', 'l', 'Î', 'î', 'M', 'm', 'N', 'n', 'É', 'é', '?'],
  ['O', 'o', 'Ï', 'ï', 'P', 'p', 'Q', 'q', 'R', 'r', '!'],
  ['Ô', 'ô', 'S', 's', 'T', 't', 'U', 'u', 'V', 'v', '“'],
  ['W', 'w', 'X', 'x', 'Y', 'y', 'Ù', 'ù', 'Z', 'z', '”'],
  ['@', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];

functiongetCoordinates(array, char) {
  for (let i = 0; i < array.length; i++) {
    const i2 = array[i].indexOf(char);
    if (i2 !== -1)
      return [i, i2]
  }
  returnundefined
}

console.log(getCoordinates(letterVariations, 'u'))
console.log(getCoordinates(letterVariations, '@'))

Note: This returns the indexes and it is zero-based. If you want [7, 7], you need to return [i+1, i2]

Solution 2:

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/indexOf

const letterVariations = [ 
		[' ','0','1','2','3','4','5','6','7','8','9'],
		['A','a','B','b','C','c','D','d','E','e',';'],
		['Â','â','F','f','G','g','H','h','Ê','ê',':'],
		['À','à','I','i','J','j','K','k','È','è','.'],
		['L','l','Î','î','M','m','N','n','É','é','?'],
		['O','o','Ï','ï','P','p','Q','q','R','r','!'],
		['Ô','ô','S','s','T','t','U','u','V','v','“'],
		['W','w','X','x','Y','y','Ù','ù','Z','z','”'],
		['@','&','#','[','(','/',')',']','+','=','-'],
];

functiongetIndexOfLetter(letter) {
  return letterVariations.reduce((result, values, index) => {
    if (result[0] > -1) return result;

    const found = values.indexOf(letter);

    return found > -1 ? [Number(index), found] : result;
  }, [-1, -1])
}

console.log(getIndexOfLetter('k'))

Post a Comment for "Get Coordinates Of An Element In Multidimentional Array In Javascript"