Home > database >  How to return all even values to the beginning of the array
How to return all even values to the beginning of the array

Time:12-02

I need to organize the arrays that are inside an array so that the first numbers in the array are even

For now I can only scroll through the arrays, I couldn't implement the logic

let matriz = [
    [5, 1, 2, 4, 7, 9],
    [2, 4, 3, 1, 7, 9],
    [1, 2, 3, 4, 5, 6],
]

for (let i = 0; i < matriz.length; i  ) {
    let innerArrLength = matriz[i].length
    for (let j = 0; j < innerArrLength; j  ) {
        if (matriz[i][j] % 2 === 0) {
            // code
        } else {
            // code
        }
    }
}

`

CodePudding user response:

You could sort the array by taking a function which returns true fro even values.

const
    move = (array, fn) => array.sort((a, b) => fn(b) - fn(a)),
    array = [5, 1, 2, 4, 7, 9];

move(array, v => v % 2 === 0);

console.log(...array);

CodePudding user response:

If you don't mind a less performant solution, filter can be very clear here:

let matriz = [
    [5, 1, 2, 4, 7, 9],
    [2, 4, 3, 1, 7, 9],
    [1, 2, 3, 4, 5, 6],
]

for (let i = 0; i < matriz.length; i  ) {
  matriz[i] = matriz[i].filter(x => x%2 == 0)
                        .concat(
                         matriz[i].filter(x => x%2 != 0))
}

console.log(matriz)

(the problem is that you traverse twice every inner array and you could do it with a single pass)

CodePudding user response:

If you are just switching index with the first even element

let matriz = [
[5, 1, 2, 4, 7, 9],
[2, 4, 3, 1, 7, 9],
[1, 2, 3, 4, 5, 6],]

for (let i = 0; i < matriz.length; i  ) {
  let innerArrLength = matriz[i].length
  for (let j = 0; j < innerArrLength; j  ) {
    if (matriz[i][j] % 2 === 0) {
        if(j === 0){
          break
        }else{
          const firstIndex = matriz[i][0];
          matriz[i][0] = matriz[i][j];
          matriz[i][j] = firstIndex
          break
        }
    } 
 }
}
console.log(matriz)

To bring the first even number to front

let matriz = [ 
 [5, 1, 2, 4, 7, 9],
 [2, 4, 3, 1, 7, 9],
 [1, 2, 3, 4, 5, 6],]

 for (let i = 0; i < matriz.length; i  ) {
  let innerArrLength = matriz[i].length
  for (let j = 0; j < innerArrLength; j  ) {
    if (matriz[i][j] % 2 === 0) {
        if(j === 0){
          break
        }else{
          const element = matriz[i][j];
          delete matriz[i][j]
          matriz[i].unshift(element)
          break
        }
    } 
 }
}
console.log(matriz)
  • Related