From array of characters, constructs an
object with index as key and character as value.
Code:
const arr =["a", "b", "c", "d", "e", "f"];
let result = arr.reduce((acc, curr, index) => {
acc[index] = curr.toString();
return acc;
}, {});
console.log(JSON.stringify(result, null, 2));
Output:
{
"0": "a",
"1": "b",
"2": "c",
"3": "d",
"4": "e",
"5": "f"
}
Explanation:
1. The code defines an array `arr` containing a series of strings.
2. It uses the `reduce` method to iterate over the array and construct an object.
3. For each element in the array, it adds a new property to the accumulator object `acc`,
using the index of the element as the key and the string value as the value.
4. Finally, it logs the resulting object as a JSON string with indentation for readability.
No comments:
Post a Comment