map,forEach,filter...数组迭代方法

161 阅读5分钟

使用情景:

创建一个新的数组时使用map,当你不需要制作一个新的数组,而是要对数据做一些事情时,就使用forEach。 当你想要判断数组中是否有某个字段时可以使用indexOf(),或者搭配map使用。

当你想要判断数组中是否存在符合某个条件的元素时可以使用some(),它会返回布尔值。

当你想要判断数组中是否每个元素都符合某个条件时可以使用every(),它会返回布尔值。

当你想要得到数组中符合一定条件的第一个元素时可以使用find()方法。

当你想要得到数组中符合一定条件的所有元素时可以使用filter,它会返回一个符合条件的新数组。

map()

      let list = [1, 1, 2, 3, 4, 5];
      let newlist = list.map((item) => {
        item = item * 2;
        return item;
      });
      console.log(list); //1, 1, 2, 3, 4, 5   基本数据类型不能修改原数组会返回新数组
      console.log(newlist); //2, 2, 4, 6, 8, 10

      let list1 = [
        { name: "wangdacui", age: "89" },
        { name: "wangdabing", age: "29" },
      ];
      let newlist1 = list1.map((item) => {
        item.name = "ddd";
        return item;
      });
      console.log(list1); //[ { name: "ddd", age: "89" },{ name: "ddd", age: "29" }, ]引用数据类型可以修改原数组数据
      console.log(newlist1); //[ { name: "ddd", age: "89" },{ name: "ddd", age: "29" },会会返回新数组

      let list = [1, 1, 2, 3, 4, 5];
      let newlist = list.map((item, index, arr) => {
        arr[index] = item * 2; //修改原数组
        item = item * 2; //修改新数组(否则新数组不会被改变)
        return item;
      });
      console.log(list); //2, 2, 4, 6, 8, 10    arr[index]能修改任何数据类型原数组
      console.log(newlist); // 2, 2, 4, 6, 8, 10

      let list1 = [
        { name: "wangdacui", age: "89" },
        { name: "wangdabing", age: "29" },
      ];
      let newlist1 = list1.map((item, index, arr) => {
        if (item.age == "89") {
          arr[index] = { name: "hhh", age: "00" };
        }
        item.name = "ddd";
        return item;
      });
      console.log(list1); //[ { name: "hhh", age: "00" },{ name: "ddd", age: "29" }, ]arr[index] 方法可以修改整个对象
      console.log(newlist1); //[ { name: "ddd", age: "89" },{ name: "ddd", age: "29" },会返回新数组

forEach()

 forEach()
      let list = [1, 1, 2, 3, 4, 5];
      let newlist = list.forEach((item) => {
        item = item * 2;
        // return item; //没有返回值不用写return
      });
      console.log(list); //1, 1, 2, 3, 4, 5   基本数据类型不能修改原数组不会会返回新数组
      console.log(newlist); //undefined

      let list1 = [
        { name: "wangdacui", age: "89" },
        { name: "wangdabing", age: "29" },
      ];
      let newlist1 = list1.forEach((item) => {
        item.name = "ddd";
        return item;
      });
      console.log(list1); //[ { name: "ddd", age: "89" },{ name: "ddd", age: "29" }, ]引用数据类型可以修改原数组数据
      console.log(newlist1); //undifined,不会会返回新数组

      let list1 = [
        { name: "wangdacui", age: "89" },
        { name: "wangdabing", age: "29" },
      ];
      let newlist1 = list1.forEach((item, index, arr) => {
        arr[index] = { name: "hhh", age: "00" };
        item.name = "ddd";
        return item;
      });
      console.log(list1); //[ { name: "hhh", age: "00" },{ name: "hhh", age: "00" }, ]  arr[index] 方法可以修改整个对象
      console.log(newlist1); //undifined,不会会返回新数组

indexOf()

如果未找到项目,Array.indexOf() 返回 -1。如果项目多次出现,则返回第一次出现的位置。
let list = [1, 1, 2, 3, 4, 5];
      let newlist1 = list.indexOf(3);
      console.log(list); //[1, 1, 2, 3, 4, 5]  不会修改原始数组数据
      console.log(newlist1); //3 返回元素位置索引

some(),every(),filter(),find()

some();
      let list = [1, 1, 2, 3, 4, 5];
      let newlist1 = list.some((item) => {
        return item > 2;
      });
      console.log(list); //[1, 1, 2, 3, 4, 5]  不会修改原始数组数据
      console.log(newlist1); //true

every();
      let list = [1, 1, 2, 3, 4, 5];
      let newlist1 = list.every((item) => {
        return item > 2;
      });
      console.log(list); //[1, 1, 2, 3, 4, 5]  不会修改原始数组数据
      console.log(newlist1); //false

filter();
      let list = [1, 1, 2, 3, 4, 5];
      let newlist1 = list.filter((item) => {
        return item > 2;
      });
      console.log(list); //[1, 1, 2, 3, 4, 5]  不会修改原始数组数据
      console.log(newlist1); //[3, 4, 5]

find();
      let list = [1, 1, 2, 3, 4, 5];
      let newlist1 = list.find((item) => {
        return item > 2;
      });
      console.log(list); //[1, 1, 2, 3, 4, 5]  不会修改原始数组数据
      console.log(newlist1); //3

reduce

数组累加累乘

数组累加是项目经常遇到的,比如计算商品总价等,使用reduce就可以一行代码搞定,而且不用定义外部变量,reduce是完全无副作用的函数。

// 累加
let list = [1, 1, 2, 3, 4, 5];
let newlist = list.reduce((a, i) => a + i);
console.log(newlist);  //16

// 累加,默认一个初始值
let newlist = list.reduce((a, i) => a + i, 5);
console.log(newlist);  //21

// 累乘
let newlist = list.reduce((a, i) => a * i);
console.log(newlist);  //120

找出数组最大值

在数组每次的迭代中,我们使用Math.max获取最大值并返回,最后我们将得到数组所有项目的最大值。

let list = [1, 1, 2, 3, 4, 5];
letnewlist = list.reduce((a, i) => Math.max(a, i));
console.log(list);  //[1, 1, 2, 3, 4, 5]
console.log(letnewlist);  //5

如果数组每项都是数字可以使用`...`展开运算符和`Math.max`配合。
letnewlist = list.reduce((a, i) => Math.max(...list));
console.log(list);  //[1, 1, 2, 3, 4, 5]
console.log(letnewlist);  //5

处理不规则数组

通过mapreduce配合使用,返回每个子数组拼接好的结果。

let data = [
            ["白色", "999g", "iphone"],
            ["王大锤", "1.2m", "女"],
          ];
let dataConcat = data.map((item) => item.reduce((a, i) => `${a} ${i}`));
console.log(dataConcat);  //['白色 999g iphone', '王大锤 1.2m 女']

删除数据重复项

检查当前迭代项是否存在,如果不存在添加到数组中。(数组去重)

let list = [1, 1, 2, 3, 4, 5];
let newlist = list.reduce((noDupes, curVal) => {
  if (noDupes.indexOf(curVal) === -1) { noDupes.push(curVal) }
  return noDupes
}, [])

console.log(newlist)// 输出:[1, 2, 3, 4, 5]

按属性分组

按照指定key将数据进行分组,这里我用国家字段分组,在每次迭代过程中检查当前国家是否存在,如果不存在创建一个数组,将数据插入到数组中。并返回数组。

let list = [  {name: '法外', job: '数据分析师', country: '中国'},  {name: '狂徒', job: '科学家', country: '中国'},  {name: '张三', job: '科学家', country: '美国'},  {name: '老师', job: '软件工程师', country: '日本'},]

let newlist = list.reduce((group, curP) => {
  let newkey = curP['country']
  if(!group[newkey]){
    group[newkey]=[]
  }
  group[newkey].push(curP)
  return group
}, [])
console.log(newlist);[                 中国: [{name: '法外', job: '数据分析师', country: '中国'},{name: '狂徒', job: '科学家', country: '中国'},] 
                日本: [{name: '老师', job: '软件工程师', country: '日本'}] 
                美国: [{name: '张三', job: '科学家', country: '美国'},] 
                ]

数组扁平化

这里展示的数组只有一级深度,如果数组是多级可以使用递归来进行处理

let list = [[3, 4, 5], [2, 5, 3], [4, 5, 6]]
let newlist = list.reduce((singleArr, nextArray) => singleArr.concat(nextArray), [])
console.log(newlist)  //[3, 4, 5, 2, 5, 3, 4, 5, 6]

当然也可以使用ES6的`.flat`方法替代
let newlist = list.flat();
console.log(newlist)  //[3, 4, 5, 2, 5, 3, 4, 5, 6]

反转字符串

这也是一种很奇妙的实现方法

let list = [..."hello world"];
console.log(list); //['h', 'e', 'l', 'l', 'o', ' ', 'w', 'o', 'r', 'l', 'd']
let newlist = list.reduce((a, v) => v + a);
console.log(newlist); //dlrow olleh
或者
[..."hello world"].reverse().join('')