A
A
Anna2018-08-15 11:33:06
JavaScript
Anna, 2018-08-15 11:33:06

How to replace elements of one array with elements of another according to a given rule?

Each number corresponds to a letter (0-A, 1-B, and so on up to 9). It is necessary to convert the input number into a set of letters corresponding to each digit of the number. Help me find the error please

var arr1 = '3649824598';
var arr2 ='АБВГДЕЖЗИК';
for (i=0; i<arr1; i++) {
    for (j=0; j<arr2; j++){
    if (arr1[i] == j) 
        arr1[i]=arr2[j];
    }
}
console.log (arr1);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Sergey Sokolov, 2018-08-15
@LShAnka

They forgot .length- they were probably going to iterate over i from 0 to the length of the string arr1. There are not arrays, but two strings.

for (i=0; i<arr1.length; i++) {
    for (j=0; j<arr2.length; j++){

The nested loop is not needed. It is enough to iterate over each digit of the input.
To find the letter corresponding to a digit i, it is enough to take the i-th element of the string arr2:
In short, in one string, this can be solved by converting the string into an array and applying a function to each element.
In one line
var arr1 = '3649824598';
var arr2 ='АБВГДЕЖЗИК';

arr1.split('').map(n => arr2[n]).join('')  // ГЖДКИВДЕКИ

  • split('') сделает из строки массив цифр;
  • map() применит к каждой цифре функцию, которая заменит цифру на соотв. букву из arr2;
  • join('') склеит элементы массива (теперь уже буквы) в одну строку.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question