There is a multidimensional array:

var arr = [ [1,2,3], [4,5,6], [7,8,9] ]; 

how to navigate it?

There is a text: Yes, I have 5.

When the number 5 is in the text, I have to replace it with 2.
When the number 7 is in the text, I have to replace it with 4.
And so on. (example at least on the movement in up, then I will understand)

You can omit everything except the function that takes the value of the variable and on its basis selects the desired value.

I would be very grateful for the help.

    3 answers 3

     var arr = [ [1,2,3], [4,5,6], [7,8,9] ]; let str='Да, у меня 9', num=parseInt(str.match(/\d+/)[0]) //выцепляем число из строки arr.some((v,i)=>{ let j=v.findIndex(v=>v===num), //ищем нужное число в одном из массивов isgood=j!=-1 //условие на то, что наши поиски успешны if(isgood){ //если число найдено let newval=arr[i-1][j] //берём массив, стоящий уровнем выше if(newval) console.log(str.replace(num,newval)) //если мы не вышли за пределы двухмерного массива, то всё впорядке, заменяем число в строке и выводим её } return isgood }) 

    Interactive primerchik:

     var arr = [ [1,2,3], [4,5,6], [7,8,9] ]; $('button').click(()=>{ let num=parseInt($('input').val()) //число из инпута arr.some((v,i)=>{ let j=v.findIndex(v=>v===num), //ищем нужное число в одном из массивов isgood=j!=-1 //условие на то, что наши поиски успешны if(isgood){ //если число найдено let newval=arr[i-1][j] //берём массив, стоящий уровнем выше if(newval) console.log($('span').text()+newval) //если мы не вышли за пределы двухмерного массива, то всё впорядке, заменяем число в строке и выводим её } return isgood }) }) 
     input{ width:20px; } 
     <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <span>Да, у меня </span><input value=5><p> <button>Преобразовать</button> 

      If I understand you correctly, you can imagine everything

      3n + 1;
      3n + 2;
      3n + 3;

      Suppose the number 5.
      We do not know the position, therefore it will be 3n + x = 5; 3n = 5-x;
      x varies from 1 to 3 and the integer number.

       function findPos(number, arr){ let pos = null; let row = null; for(let i = 1; i <= 3; i++) { if((number - i) % 3 === 0) { const temp = (number - i) / 3; pos = i - 1; row = temp === 0 ? temp : temp - 1; break; } } console.log(arr[row][pos]); } var arr = [ [1,2,3], [4,5,6], [7,8,9] ]; findPos(5, arr); findPos(7, arr); findPos(3, arr); 

        No fuss. But I think it would be possible to write something even shorter, I did not think of it.

         const arr = [ [1, 2, 3], [4, 5, 6], [7, 8, 9] ] function get (arr, find) { let columns = arr.length let joined = [].concat(...arr) let index = joined.indexOf(find) + 1 let column = Math.ceil(index / joined.length * columns) - 1 let indexUp = arr[column].indexOf(find) let upColumn = arr[column - 1] return (upColumn && upColumn[indexUp]) || null } console.log(get(arr, 8)) // 5 console.log(get(arr, 6)) // 3 console.log(get(arr, 3)) // null