Viết hàm tính tỷ lệ phần trăm (phân số) của số âm, zero, số dương trong mảng.
Ví dụ: [23,-1,0,11,18] → [0.2, 0.2, 0.6] (âm, zero, dương).
Ví dụ
const arr = [23, -1, 0, 11, 18];
const findRatio = (arr = []) => {
const { length } = arr;
const res = [0, 0, 0];
for (let i = 0; i < arr.length; i++) {
const el = arr[i];
const key = el / Math.abs(el || 1);
res[key + 1]++;
}
return res.map(el => el / length);
};
console.log(findRatio(arr));
Kết quả
[0.2, 0.2, 0.6]