使用ES6功能在数组中移动零 [英] Move zeroes in array using ES6 features

查看:71
本文介绍了使用ES6功能在数组中移动零的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是ES6的新手,尝试制作一个函数,以将数组中的所有零移动到数组的最后一个位置,同时保留数组的原始顺序例如. [1,0,0,0,2,3,4,5] => [1,2,3,4,5,0,0,0]

I’m new to ES6, trying to make a function that moves all zeros in the array in the last position of the array while preserving the original order of the array E.g. [1,0,0,0,2,3,4,5] => [1,2,3,4,5,0,0,0]

 function moveZeros (arr) {
  let zeroArr = [];
    for(let i = 0;i < arr.length;i++) {
    if (arr[i] == 0) {
     zeroArr.push(arr[i]);
     arr.splice(i, 1);
    }
  }
  arr.push(...zeroArr);
  return arr;
} 

这是我的代码,可以正常工作,但是我认为使用某些ES6功能可以使此代码更短.有人可以提供更好的解决方案

This is my code its works fine, but I think this can be shorter more in using some ES6 features. Can someone provide a better solution

推荐答案

使用 filter 函数和 spread 运算符.

const moveZeros = arr => {
  const z = arr.filter(a => a === 0); // get all zeroes
  const nZ = arr.filter(a => a !== 0); // get all non zeroes
  return [...nZ, ...z]; // put the zeroes on the last position
};

这篇关于使用ES6功能在数组中移动零的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆