Using `Map` how do I write a function that converts an array of farenheit values to celcius?

Viewed 666

I'm am very new to programming and I am trying to solve a problem where I have to convert an array of Fahrenheit values, to Celsius. Though I am not too sure where to start with .map and I would really appreciate some help in understanding how to solve this problem.

This was my first attempt in trying to solve the test problem.

function convertTemps(array) {
  return array * (9/5) + 32
}

These are the problems I am trying to solve

describe('convertTemps', () => {
  it('should convert farenheit to celcius for all temperatures in the array', () => {
    expect(convertTemps([23, 140, 212, 41])).to.deep.equal([-5, 60, 100, 5])
    expect(convertTemps([-58, -22, -4, 14])).to.deep.equal([-50, -30, -20, -10])
    expect(convertTemps([104, 122, 158, 176])).to.deep.equal([40, 50, 70, 80])
  })
})
3 Answers

What you've written is the function that should run for each item in the array, better known as the callback or the predicate. All you have to do is move that exact function into an Array.map().

Note that your formula for °F -> °C is incorrect. The correct formula is (°F − 32) × 5/9 = °C

Here's a slightly verbose way that demonstrates simply moving your function into the .map:

function convertTemps(array) {
  return array.map(                // for every value in the array
    function(temp) {               // run this function
      return (temp - 32) * 5 / 9
    }
  );
}

var array = [23, 140, 212, 41];
var result = convertTemps(array);

console.log(result);

If you prefer ES6:

const convertTemps = (array) => array.map(temp => (temp-32) * 5/9);

const array = [23, 140, 212, 41];
const result = convertTemps(array);
console.log(result);

If you can use es6 (arrow functions)

function convertTemps(array) {
    return array.map(element => element * (9/5) + 32);
}

Map is simple, either pass an inline function describing what to do with each item in the array, or define a separate function and pass it in the the map function

//inline map
function convertTemps(array) {
  return array.map(temp => temp * (9/5) + 32)
}


//external function
function convertTemp(temp) {
  return temp * (9/5) + 32;
}

function convertTemps(array) {
  return array.map(convertTemp)
}

Related