Etika49
Etika49

Reputation: 742

compare numbers from one array with numbers of another and return results

I have two arrays:

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

I need to compare each number from array1 with each number of array2 and if the number from array1 is less than a number from array2, assign the result to the results array.

e.g 0,1 is >0 and <1 0.3 is > 0 and <1 ..

the function should return the following:

let results = [2, 1, 0 ,1, 0, 0]
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)
  })

Upvotes: 0

Views: 67

Answers (2)

felix
felix

Reputation: 56

Is this what you are looking for

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;
});

Upvotes: 1

Alberto
Alberto

Reputation: 12929

You can do something like this:

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)

Upvotes: 1

Related Questions