convertType(arr) {
let resultArr = arr.map(arr => {
if (arr == '0') {
return 'zero'
}
if (arr == '1') {
return 'one'
}
if (arr == '2') {
return 'two'
}
if (arr == '3') {
return 'three'
}
})
return resultArr;
}
i need to find maybe a better solution for this loop and how to get these results back in a better way. Okay there is always a "switch" loop but what do you think about this? is it good?
This is work good , but i want better solution.
forEach() loop: Each element of the array is subjected to a function performing some operation or task. The function is specified as a parameter of the forEach method in JavaScript. It performs highly efficient tasks where functional code is required.
> filter() The most common way was to use for loop, iterate elements and find which is even. Instead of using for in this case, we can use the filter() method. This method also returns a new array.
forEach loop The forEach method in Javascript iterates over the elements of an array and calls the provided function for each element in order. The execution time of forEach is dramatically affected by what happens inside each iteration. It is fast and designed for functional code.
You use the break statement to terminate a loop early such as the while loop or the for loop. If there are nested loops, the break statement will terminate the innermost loop. You can also use the break statement to terminate a switch statement or a labeled statement.
I'd make an array and look up indicies:
const numbers = ['zero', 'one', 'two', 'three'];
convertType(arr) {
return arr.map(item => numbers[item]);
}
If the values being compared against aren't array indicies or might not have all values starting from 0, use an object:
const numbers = {
2: 'two',
3: 'three'
somethingElse: 'something else'
};
with the same code for convertType
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With