The task is the following - in input
there are some English letters which I want to replace by values located in jap
and put in outputArr
according to dictionary in eng
(same position).
But I really don't understand how to make such loop / if to make it work.
<script>
var input = "agde";
var inputArr = input.split('');
var outputArr = [];
var eng= ["a","b","c","d","e","f","g"];
var jap = ["あ","び","を","ご","で","え","よ"];
CodePudding user response:
First combine eng
and jap
into a lookup table (a plain object):
var eng = ["a","b","c","d","e","f","g"];
var jap = ["あ","び","を","ご","で","え","よ"];
var translation = Object.fromEntries(eng.map((letter, i) => [letter, jap[i]]));
// Now translate an example input
var input = "agde";
var output = Array.from(input, letter => translation[letter]).join("");
console.log(output);
CodePudding user response:
You can map the array and use the indexOf
method from Arrays to find the index of English alphabet and use it against the jap array
var input = "agde";
var eng= ["a","b","c","d","e","f","g"];
var jap = ["あ","び","を","ご","で","え","よ"];
const getJapOut = ([...input]) => [...input].map(value => jap[eng.indexOf(value)])
console.log(getJapOut(input));
CodePudding user response:
You can make use of indexOf
function to get the corresponding index, access it via []
and map
the result into your outputArr
:
var eng = ["a", "b", "c", "d", "e", "f", "g"];
var jap = ["あ", "び", "を", "ご", "で", "え", "よ"];
var input = "agde";
var inputArr = input.split("");
const outputArr = inputArr.map((char) => jap[eng.indexOf(char)]);
console.log(outputArr);
CodePudding user response:
Using findIndex()
we can get the corresponding Japanese character and use map()
to create a new array with the new characters.
var input = "agde";
var inputArr = input.split("");
var outputArr = [];
var eng = ["a", "b", "c", "d", "e", "f", "g"];
var jap = ["あ", "び", "を", "ご", "で", "え", "よ"];
let output = inputArr.map((char) => {
const index = eng.findIndex((letter) => letter === char);
return jap[index];
});
console.log(output);