const arr = ['a','c','o','l','s','t','r','i','n','g'];
let str = arr[1,2,2,3];
//returns l
What can i do to efficiently return "cool" which is what i want?
technically I'm doing this with all of the special characters as a way to reference them in string functions cause my code kept breaking otherwise.I found this fast, easy, and efficient;
The only reasonable solution I can think of is to capitalize the array and create a function with the lowered case and have that return a concatenated version. Am hoping for a better suggestion;
CodePudding user response:
You need to take the indices and map the characters. Then join the array to a string.
const
array = ['a', 'c', 'o', 'l', 's', 't', 'r', 'i', 'n', 'g'],
indices = [1, 2, 2, 3],
string = indices.map(i => array[i]).join('');
console.log(string);
CodePudding user response:
If you have an array of the indexes of the characters in 'arr', you can create a string as following:
const arr = ['a','c','o','l','s','t','r','i','n','g'];
const indexes = [1,2,2,3]
const concatenated = indexes.map(el => arr[el]); // result: ['c', 'o', 'o', 'l']
const string = concatenated.join(''); // result 'cool'
CodePudding user response:
Well since you prefer hard code here is what you can do to generate the string "cool". We simply create a new array of hard coded index values that generates the cool array and simply join them together!
const arr = ['a','c','o','l','s','t','r','i','n','g'];
let newArr = [arr[1],arr[2],arr[2],arr[3]];
newArr will be [c,o,o,l]
let string = newArr.join("");
string will be join with no spaces returning "cool"
CodePudding user response:
Use a loop to access the array elements at each index and append them to the result string.
const arr = ['a','c','o','l','s','t','r','i','n','g'];
let str = '';
[1, 2, 2, 3].forEach(index => str = arr[index]);
console.log(str);
