skip to Main Content
const arrayA = [5.2, 3, 3.5, 2.7, 3.3, 5, 2.9];
const arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9]
const arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4]

In these arrays, the common min and max values are from that part enter image description here

How can I get the min and max value in JavaScript or using lodash?

3

Answers


  1. You could take the common values and get min and max value from this set.

    const
        arrayA = [5.2, 3, 3.5, 2.7, 3.3, 5, 2.9],
        arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9],
        arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4],
        common = [arrayA, arrayB, arrayC].reduce((a, b) => a.filter(v => b.includes(v)));
    
    console.log(common);
    console.log(Math.min(...common));
    console.log(Math.max(...common));
    Login or Signup to reply.
  2. Lodash version, using _.intersection _.min and _.max :

    const arrayA = [5.2, 3, 3.5, 2.7, 3.3, 5, 2.9];
    const arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9];
    const arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4];
    
    const commonVals = _.intersection(arrayA, arrayB, arrayC);
    
    const commonMin = _.min(commonVals);
    const commonMax = _.max(commonVals);
    
    console.log("Common min:", commonMin);
    console.log("Common max:", commonMax);
    console.log("Common vals:", commonVals);
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.21/lodash.min.js"></script>
    Login or Signup to reply.
  3. If you don’t want to use the Math.min and Math.max functions, I provided an altenartive solution. We basically just merge all 3 arrays into one and only keep the common values. hen we find the min and max manually by iterating through the array.

    const arrayB = [1, 2.2, 7, 3, 3.2, 2.7, 6.2, 1.9, 3.3, 2, 9]
    const arrayC = [2.7, 3, 3.3, 8, 2.7, 5, 1.5, 4]
    
    //we combine the arrays and only keep the common values
    const commonValues = [arrayA, arrayB, arrayC].reduce((a, b) => a.filter(v => 
    b.includes(v)));
    
    let min = Number.MAX_VALUE
    let max = Number.MIN_VALUE
    
    for (let i = 0; i < commonValues.length; i++) {
      if (min > commonValues[i]) {
        min = commonValues[i]
      }
      if (max < commonValues[i]) {
        max = commonValues[i]
      }
    }
    
    console.log(min) 
    console.log(max)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search