Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Better solution for this loop and return data ? Javascript [closed]

Tags:

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.

like image 945
vidov63 Avatar asked Jan 09 '21 19:01

vidov63


People also ask

Which loop is more efficient in JavaScript?

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.

What can I use instead of for loop in JavaScript?

> 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.

What is faster than for loop in JavaScript?

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.

How do you stop a loop when a condition is met JavaScript?

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.


1 Answers

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.

like image 144
CertainPerformance Avatar answered Sep 30 '22 13:09

CertainPerformance