Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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)

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

 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)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading