Javascript ouput a number closest to zero with an array that has used a .map function

Button Press :

I am trying to output the number closest to zero from an array that has both a string and an int, so I used a .map function to get only the array's int values. But the code below that I have tried only outputs

JavaScript error: Uncaught SyntaxError: Identifier 'productProfitArray' has already been declared on line

Not sure where could I move the .map function to get the ints. This is the only tricky part for me since I need to get rid of the array's string value. Any help would be appreciated.

var productProfitArray = [{
    "Product A": -75
  },
  {
    "Product B": -70
  },
  {
    "Product C": 98
  },
  {
    "Product D": 5
  }, // Profit nearest to 0
  {
    "Product E": -88
  },
  {
    "Product F": 29
  }
];

function zeroProfitProduct(productProfitArray) {
  const needle = 0;
  const productProfitArray.map(o => Object.values(o)[0]).reduce((a, b) => {
    return Math.abs(b - needle) < Math.abs(a - needle) ? b : a;
  });
}

var zeroProfitProductValue = zeroProfitProduct(productProfitArray);
document.write('Profit nearest to 0 is:  ' + zeroProfitProductValue);

OliverRadini :

This should do it; you need to return from your function rather than declare a const

var productProfitArray = [ 
{"Product A": -75},
{"Product B": -70},
{"Product C": 98},  
{"Product D": 5},   // Profit nearest to 0
{"Product E": -88},
{"Product F": 29}
];

function zeroProfitProduct(productProfitArray) {
    const needle = 0;
    return  productProfitArray.map(o => Object.values(o)[0]).reduce((a, b) => {
      return Math.abs(b - needle) < Math.abs(a - needle) ? b : a;
    });
}

var zeroProfitProductValue = zeroProfitProduct(productProfitArray);
document.write('Profit nearest to 0 is:  ' + zeroProfitProductValue);

A better solution would be to reduce; typically when you are going from many values to one, reduce is a good tool to use:

var productProfitArray = [ 
{"Product A": -75},
{"Product B": -70},
{"Product C": 98},  
{"Product D": 5},   // Profit nearest to 0
{"Product E": -88},
{"Product F": 29}
];

const takeFirstValue = o => Object.values(o)[0];
const takeLowest = (x, y) => x < y ? x : y;
const compose = f => g => x => f(g(x));

const takeFirstValueAndMakeAbsolute = compose(Math.abs)(takeFirstValue)

function zeroProfitProduct(productProfitArrayIn) {

  return productProfitArrayIn
    .map(takeFirstValueAndMakeAbsolute)
    .reduce(takeLowest);
}

var zeroProfitProductValue = zeroProfitProduct(productProfitArray);
document.write('Profit nearest to 0 is:  ' + zeroProfitProductValue);

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=29771&siteId=1