Search code examples
javascriptarrayslistsortingnumbers

Find closest array given list of arrays


Given a list of arrays in a variable, how can I find the index from the most closest array to the main array that I have? I need a function that does this by the numerical values of each index of the arrays and also keep in mind the length of the arrays if possible.

function findClosestArray(x, list){
     //Array comparing code here
}
let mainArr = [2237, 2192, 2234, 2223, 2196, 2279, 2160, 2123, 2063];
let otherArrays = [
     [1757, 1650, 1757, 1774, 1755, 1615, 1591, 1550]
     [1678, 1545, 1742, 1605, 1662, 1629, 1678, 1601]
];
let closestArr = findClosestArray(mainArr, otherArrays);
//Expected output: 0 or 1 (index of otherArrays)

Solution

  • The OP haven't described what is 'closest'. But given the same array length we could calculate ratios between array items. The more the ratio is closer to 1 the more similar the array items. Then we sum all the ratios as an value how close 2 arrays are and find the closest array from the list. If the arrays are identical the sum would be equal to the length of the arrays:

    let mainArr = [2237, 2192, 2234, 2223, 2196, 2279, 2160, 2123];
    let otherArrays = [
         [1757, 1650, 1757, 1774, 1755, 1615, 1591, 1550],
         [1678, 1545, 1742, 1605, 1662, 1629, 1678, 1601]
    ];
    
    let closestArr = findClosestArray(mainArr, otherArrays);
    
    console.log(closestArr);
    
    function findClosestArray(arr, list){
        
        // get sum of ratios between array items
        const getHowClose = (arr,arr2) => arr.map((item,i) => item/arr2[i]).reduce((sum,item) => sum+item);
    
        const ratios = list.map(arr2 => getHowClose(arr, arr2));
        console.log(...ratios);
    
        // find index with the smallest average ratio
        return ratios.reduce((min, item, i) => !min || min[0] > item ? [item, i] : min, 0)[1];
            
    }