This function current takes in an array, and outputs it a character with its count if the element's length is greater than one
Is there a way I can do this same thing, perhaps with a different javascript array method without having to use a new array or a result variable?
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => {
let newArray = [];
let result = arr.forEach(e => e.length > 1 ? newArray.push(`${e[0]}${e.length}`) : newArray.push(e))
return newArray.join("");
}
console.log(compressCharacters(a));
3 Answers 3
You can just use map() instead of forEach() and return the values you want. There's no need for the extra array. It's often the case than forEach + push() == map()
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => {
return arr.map(e => e.length > 1
? `${e[0]}${e.length}`
: e)
.join("");
}
console.log(compressCharacters(a));
Comments
You can construct and immediately return a mapped array, that's joined by the empty string:
const a = ['aaa', 'z', 'eeeee'];
const compressCharacters = arr => (
arr.map(str => str[0] + (str.length > 1 ? str.length : ''))
.join('')
)
console.log(compressCharacters(a));
When you're trying to construct a new array by transforming all elements from some other array, .map is the appropriate method to use. forEach should be reserved for generic iteration with side effects, when you aren't trying to construct a new object. (when you are trying to construct a new object, but it's not an array, or the new array isn't one-to-one with the old array, usually you can use .reduce)
Comments
This is an alternative using the function reduce to build the desired output.
const a = ['aaa', 'z', 'eeeee'],
result = a.reduce((a, [m], i, arr) => {
let {length} = arr[i];
return a + m + (length <= 1 ? "" : length);
}, "");
console.log(result);