Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Try to give an alternative in this question WITHOUT LOOPING! Just using indexOf and some integer math

Get coordinates of an element in multidimentional array in Javascript

The code below seemed promising but fails.

Anyone with better math skills feel like fixing it?

var letterVariations = [ 
		[' ','0','1','2','3','4','5','6','7','8','9'],
		['A','a','B','b','C','c','D','d','E','e',';'],
		['?','a','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','”'],
		['@','&','#','[','(','/',')',']','+','=','-'],
	];

var string = JSON.stringify(letterVariations);
var pos = string.indexOf("u")
console.log(Math.floor((pos/10)%8),pos%10)

// fails, how to fix?
pos = string.indexOf("M")
console.log(Math.floor((pos/10)%8),pos%10)
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
275 views
Welcome To Ask or Share your Answers For Others

1 Answer

function findPos(array, symbol) {
  const string = array.toString().replace(/,/g, '');
  const pos = string.indexOf(symbol)

  const d = (array[0] || []).length

  const x = pos % d;
  const y = Math.floor(pos / d)

  return { x, y }
}

const array = [
  [' ', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'],
  ['A', 'a', 'B', 'b', 'C', 'c', 'D', 'd', 'E', 'e', ';'],
  ['?', 'a', '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', '”'],
  ['@', '&', '#', '[', '(', '/', ')', ']', '+', '=', '-'],
];


console.log(findPos(array,' ')) //=> [0, 0]
console.log(findPos(array,'M')) //=> [4, 4]
console.log(findPos(array,'u')) //=> [6, 7]
console.log(findPos(array,'-')) //=> [8, 10]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...