javascript 如何将所有偶数值返回到数组的开头

bvk5enib  于 2022-12-02  发布在  Java
关注(0)|答案(3)|浏览(139)

我需要组织数组中的数组,使数组中的第一个数字为偶数
现在我只能滚动数组,无法实现逻辑``

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
        }
    }
}

`

hm2xizp9

hm2xizp91#

你可以用一个函数对数组进行排序,该函数返回偶数值的true

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);
7lrncoxx

7lrncoxx2#

如果您不介意性能较低的解决方案,filter在这里可以非常清楚:

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问题是,您需要遍历每个内部数组两次,而只需一次即可)

kse8i1jr

kse8i1jr3#

如果您只是使用第一个偶数元素切换索引

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)

将第一个偶数置于最前面

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)

相关问题