버튼을 눌러 :
난 단지 배열의 INT 값을 얻기 위해 .MAP 기능을 사용 그래서 나는, 출력에 문자열과 int로 모두가 배열에서 숫자 0에 가장 가까운을 시도하고있다. 그러나 아래의 코드가 난 단지 출력을 시도하는 것이
자바 스크립트 오류 : catch되지 않은 구문 에러 : 식별자 'productProfitArray가'이미 줄에 선언 된
확실하지 난의 int를 얻기 위해 .MAP 기능을 이동할 수있는 곳. 내가 배열의 문자열 값을 제거 할 필요가 있기 때문에 이것은 나를 위해 유일한 까다로운 부분이다. 어떤 도움을 주시면 감사하겠습니다.
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 :
이 그것을해야한다 당신은 선언 (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);
더 나은 솔루션이 감소하는 것; 일반적으로는, 하나에 많은 값에서가 감소 할 때 사용할 수있는 좋은 도구입니다 :
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);