javascript

Compare elements of array based on position of elements


I need to compare array first position with the one in the last position, the second with the second to last one, and so on. Using javascript.

[1, 2, 3, 4, 5, 6]

1 with 6, 2 with 5, and 3 with 4

The real deal, I need to compare properties of objects if it is equals I need to compare another property (note and year)

 function compare(arr) {
        const n = arr.length
        const mid = Math.floor(n / 2)
        const second = [];
        for (let i = 0; i < mid; i++) {
           if (arr[i].note === arr[n - i - 1].note) {
                if (arr[i].year > arr[n - i - 1].year) {
                    second.push(arr[i])
                } else {
                    second.push(arr[n - i - 1])
                }
            } else if (arr[i].note > arr[n - i - 1].note) {
                second.push(arr[i])
            } else {
                second.push(arr[n - i - 1])
            }
        }
        return second
    }

Solution

  • You could iterate half of the array and compare the element with the opposite one

    function compare(arr) {
      const n = arr.length
      const mid = Math.floor(n / 2)
    
      for (let i = 0; i < mid; i++) {
        console.log("comparing", arr[i], "and", arr[n - i - 1])
        // do your comparision
      }
    }
    
    arr = [1, 2, 3, 4, 5, 6]
    compare(arr)
    
    console.log('---')
    
    arr = [1, 2, 3, 4, 5]
    compare(arr)