I am trying to map an array of strings
arrString = [
["A", "B"],
["C", "D"],
["E", "F"],
["D", "A"],
["F", "C"],
["G", "E"]
]
based on an object of key values:
map = {
'0': 'A',
'1': 'B',
'2': 'C',
'3': 'D',
'4': 'E',
'5': 'F',
'6': 'G'
}
into an array of numbers
arrNum = [
["0", "1"],
["2", "3"],
["4", "5"],
["3", "0"],
["5", "2"],
["6", "4"]
]
This is what I have done:
const map = {}
const arrNum = Array.from(new Array(arrString.length), () => new Array(arrString[0].length).fill([]));
for(let i = 0; i < arr2.length; i++){
map[i] = arr2[i]
}
for(let ele in arrString){
// I can't figure out how to if the obbject value is equal to ele push it's key to arrNum
if (Object.values(map).includes(ele))
}
As you can see I am trying to loop through arrString and then if any element equals a value in map I want to add its key to arrNum.
So anyone knows how to do it so I can end up with arrNum
?
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ] map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' } const arrNum = arrString.map(as => as.map(a => { for(const k in map){ if (map[k] === a) return k; } })); console.log(arrNum);
You can use:
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ]; map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' }; const keys = Object.keys(map); const arrNum = arrString.map(item => item.map(value => keys.find(key => map[key] === value))); console.log(arrNum);
First invert the map, then use it to match the letters.
const arrString = [ ["A", "B"], ["C", "D"], ["E", "F"], ["D", "A"], ["F", "C"], ["G", "E"] ] const map = { '0': 'A', '1': 'B', '2': 'C', '3': 'D', '4': 'E', '5': 'F', '6': 'G' } const invertedMap = Object.fromEntries(Object.entries(map).map(([a,b])=>[b,a])) console.log('Inverted Map:',invertedMap) const output = arrString.map(inner => inner.map(char => invertedMap[char])) console.log('Result:',output)
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.