比较一个数组中的数字与另一个数组中的数字并返回结果



我有两个数组:

const array1 = [0.1, 0.3, 1.2, 3.4]
const array2 = [0, 1, 2, 3, 4, 5]

我需要比较array1的每个数字与array2的每个数字,如果array1的数字小于array2的数字,则将结果赋值给结果数组。

e。g0,1是>0和<10.3为>1 .

函数应该返回以下内容:

let results = [2, 1, 0 ,1, 0, 0]
  • 两个数小于1,1个数小于2和>
const array1 = [0.1, 0.3, 1.2, 3.4]
const array2 = [0, 1, 2, 3, 4, 5]
let results = []
let counter = 0
array1.map( item => {
array2.map( item2 => {
if (item <= item2) {
counter += 1
}
})
results.push(counter)
})

你可以这样做:

const array1 = [0.1, 0.3, 1.2, 3.4] 
const array2 = [0, 1, 2, 3, 4, 5]
const ranges = [];
// create an array with pair of elements that will be the "upper bound" and the "lower bound"
for(let i = 0; i < array2.length - 1; i++){
ranges.push([array2[i], array2[i + 1]])
}
// for each pair of values, let's calculate the number of element greater that l (lower) and less than u (upper)
const res = ranges.map(([l, u]) => array1.filter(el => el > l && el < u).length)
console.log(res)

这是你要找的吗

const array1 = [0.1, 0.3, 1.2, 3.4];
const array2 = [0, 1, 2, 3, 4, 5];
const finalResults = array2.map((a,index,arr)=>{

//get the upper and lower limits e.g 0 and 1,1 and 2
const lowerLimit = a;
const upperLimit = arr[index + 1]? arr[index+1] : a;
//look for the elements in array1 that fit the limits
const results = array1.filter((i)=>{
return (i >= lowerLimit && i <= upperLimit);
})

return results.length;
});

最新更新