Home > Mobile >  Compare elements of array based on position of elements
Compare elements of array based on position of elements

Time:09-28

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
    }

CodePudding user response:

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)

CodePudding user response:

let arr = [1, 2, 3, 4, 5, 6];

for (let i = 0; i < arr.length; i  ) {
    console.log(`i = ${i}, element: ${arr[i]}, mirrored: ${arr[arr.length - i - 1]}`);
}

I think this is what you need

Output:

i = 0, element: 1, mirrored: 6
i = 1, element: 2, mirrored: 5
i = 2, element: 3, mirrored: 4
i = 3, element: 4, mirrored: 3
i = 4, element: 5, mirrored: 2
i = 5, element: 6, mirrored: 1
  • Related