javascriptarraysfilter

Getting the Index of the elements from an array that when substracted to the elements with same index from another array is negatif


As indicated in the question (maybe not properly formulated) I am trying to get the index of an array for which the difference between each of its element and the index-corresponding element of the second array is < 0. Maybe the code below will explain more what I am trying to obtain. I succeded to get the desired indexes using flatMap() function but could not get it using the filter() function which I think is more appropriate in this case (always getting here the element but not the index)

let array1 = ['524', '587', '034', '816', '65', '7']
let array2 = ['3', '0', '33', '4', '193', '13']



function getSumOfArrays(array1, array2){
    let sumArray = array1.map((elem,idx)=>parseFloat(elem) - parseFloat(array2[idx]))
    return sumArray
}

function getIdxNegativeDiff1(array1, array2){   //this function works   
    let negatifIdx1 = array1.flatMap((elem,idx)=>{return parseFloat(elem)-parseFloat(array2[idx]) < 0 ? idx : [] })
    return negatifIdx1
}

function getIdxNegativeDiff2(array1, array2){          
    let negatifIdx2 = array1.filter((elem,idx)=>{ return (parseFloat(elem)-parseFloat(array2[idx]) < 0 ? idx : '')})
    return negatifIdx2
}



console.log(array1)
console.log(array2)
console.log(getSumOfArrays(array1, array2))
console.log(getIdxNegativeDiff1(array1, array2))
console.log(getIdxNegativeDiff2(array1, array2))

Tried many possibilities but could not reach the solution with filter. Could someone with the solution


Solution

  • You're really close! getIdxNegativeDiff2() is filtering the differences that are <0, you just need to find the indices of those values in the original array(s), and you can do that with Array.map():

    let array1 = ['524', '587', '034', '816', '65', '7']
    let array2 = ['3', '0', '33', '4', '193', '13']
    
    
    function getIdxNegativeDiff2(array1, array2){          
        let negatifIdx2 = array1.filter(
            (elem,idx)=>{ 
            return (parseFloat(elem)-parseFloat(array2[idx]) < 0 ? idx : '')
          }
        ).map(el => array1.indexOf(el)) 
        return negatifIdx2
    }
    
    console.log("array1",array1)
    console.log("array2",array2)
    
    console.log("getIdxNegativeDiff2",getIdxNegativeDiff2(array1, array2))