数组常见操作整理

212 阅读7分钟

背景

为什么要写这篇文章?因为在学习数据结构的过程中,会涉及到一些数组的操作,但是记的不清晰。想通过这一波整理,能帮助到自已,也帮助到别人。

slice方法

定义:返回一个新的数组(不会改变原有的数组),包含从 start 到 end (不包括该元素)的 arrayObject 中的元素

const arr = [1, 2, 3, 4,5]
const selectArr = arr.slice(1,3); 
console.log(selectArr) // [2,3] 这里是不包括结束end的元素的

image.png

splice方法

定义:向数组中添加/删除项目,然后返回被删除的项目。

splice(index, howmany, item1...itemx),这个方法是拥有三个参数。
index: 必需。整数,规定添加/删除项目的位置,使用负数可从数组结尾处规定位置。
howmany: 必需。要删除的项目数量。如果设置为 0,则不会删除项目。
item1...itemX: 	可选。向数组添加的新项目。

对这个方法的个人感受:在开发的过程中,使用的还是很多,而且场景也很多。在这里就罗列一些,实际情况的使用。

删除元素

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

// 删除数组前两项
let del = arr.splice(0, 2);
console.log(del); // [1, 2] 这里说明:splice方法会返回被删除的值
console.log(arr); // [3, 4, 5] 这里说明:splice方法会改变原本的数组

// 删除指定位置的值
let del = arr.splice(1, 2); // 从index的1开始作删除,然后删除两项,所以是2和3被删除
console.log(del); // [2, 3] 
console.log(arr); // [1, 4, 5]

插入元素

let arr = ['apple', 'orange']

// 从指定位置插入元素
let add = arr.splice(1, 0, 'banana', 'watermelon')
console.log(add); // [] 因为这里没有删除任何元素,所以返回为空
console.log(arr); // ['apple', 'orange', 'banana', 'watermelon']

替换元素

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

// 替换指定位置元素
let replace = arr.splice(0, 2, 'banana', 'watermelon'); // 删除了1和2,替换为banana和watermelon

console.log(replace) // [1, 2] 被删除的元素
console.log(arr) // ['banana', 'watermelon', 3, 4, 5]

split方法

定义:把一个字符串分割成字符串数组。

string.split(‘separator:分割符’, 'howmany:长度')
separator: 必需。字符串或正则表达式,
howmany: 可选。可指定返回的数组的最大长度。
// 不传howmany参数的例子
let words = 'hello';
let arr = words.split('');  
console.log(arr); // 会返回一个新数组,而不会修改原有变量words。 ['h','e','l','l','o']

image.png

// 传howmany的例子
let words = 'hello';
let arr = words.split('', 3);  
console.log(arr); // 数组长度不可超过3,所以为 ['h','e','l']

image.png

conbat方法

定义:用于连接两个或多个数组。该方法不会改变现有的数组,仅会返回被连接数组的的一个副本。

let arr1 = ['banana','watermanlen'];
let arr2 = ['apple'];
let arr3 = arr1.conbat(arr2);
console.log(arr3); // ['banana','watermelen','apple' ]

includes方法

定义:用来判断一个数组是否包含一个指定的值,根据情况,如果包含则返回 true,否则返回false。

const arr = [1, 2, 3]
const result  = arr.includes(2);
console.log(result); // true

indexOf方法

定义:返回在数组中可以找到一个给定元素的第一个索引,如果不存在,则返回-1。

注意:string字符串也有类似的indexOf方法

const arr = [1, 2, 3]
const result = arr.indexOf(2);
console.log(result); // 1, 因为元素2位于数组的索引1。

lastIndexOf方法

定义:返回指定元素(也即有效的 JavaScript 值或变量)在数组中的最后一个的索引,如果不存在则返回 -1,从数组的后面向前查找。

const arr = ['Dodo', 'Tiger', 'Penguin', 'Dodo']
const result1 = arr.lastIndexOf('Dodo');
console.log(result); // 3
const result2 = arr.lastIndexOf('Tiger');
console.log(result); // 1

toString方法

定义:返回一个字符串,表示指定的数组及其元素。

const array1 = [1, 2, 'a', 'b'];
console.log(array1.toString()); //  "1,2,a,b"

join方法

定义:将一个数组的所有元素连接成一个字符串并返回这个字符串。如果数组只有一个项目,那么将返回该项目而不使用分隔符。

const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join()); // "Fire,Air,Water"
console.log(elements.join('')); // "FireAirWater"
console.log(elements.join('-')); // "Fire-Air-Water"

push方法

定义:将一个或多个元素添加到数组的末尾,并返回该数组的新长度。

pop方法

定义:从数组中删除最后一个元素,并返回该元素的值。此方法更改数组的长度。

const arr = [1, 2, 3, 4, 5];
console.log(arr.pop()); // 5
console.log(arr); // Array [1, 2, 3, 4]

unshift方法

定义:将一个或多个元素添加到数组的开头,并返回该数组的新长度(该方法修改原有数组 )

const array1 = [1, 2, 3];

console.log(array1.unshift(4, 5)); // 5

console.log(array1); // Array [4, 5, 1, 2, 3]

shift方法

定义:数组中删除第一个元素,并返回该元素的值。此方法更改数组的长度。

const arr = [1, 2, 3, 4, 5];
console.log(arr.shift()); // 1
console.log(arr); // Array [2, 3, 4, 5]

find方法

定义:为数组的每个元素都调用一次函数执行,返回数组中通过测试的第一个值。

let ages = [6, 8, 10, 18, 20];
ages.find(age => age >= 18) // 18, 返回的是数组中测试通过的第一个
ages.find(age => age > 30) // undefined, 找不到则返回undefined

findIndex方法

定义:为数组的每个元素都调用一次函数执行,返回数组中通过测试的第一个值的位置

let ages = [6, 8, 10, 18, 20];
ages.find(age => age >= 18) // 3, 返回的是数组中测试通过的第一个的位置
ages.find(age => age > 30) // -1, 如果没有符合条件的元素返回 -13

filter方法

定义: 创建一个新的数组,新数组中的元素是通过检查指定数组中符合条件的所有元素。若没有匹配的元素,则返回空数组。

let ages = [6, 8, 10, 18, 20];
ages.filter(age => age >= 18); // [18, 20]
ages.filter(age => age > 100) // [], 没有找到对应的值,返回空数组

map方法

定义:创建一个新的数组,数组中的元素为原始数组元素调用函数处理后的值。

let ages = [1, 2, 3, 4, 5];
// 把原本的数组元素 * 2 ,形成一个新数组返回回来。
let maps = ages.map(item => item * 2);
console.log(maps) // [2, 4, 6, 8, 10]

forEach方法

定义:对数组的每个元素执行一次给定的函数。参数如下

currentValue(必填):数组中正在处理的元素。
index(可选):数组中正在处理的元素的索引
array(可选):正在操作的数组。

举例:循环输出

const ages = [1,2];
ages.forEach((item, index, arr) => console.log(item, index, arr));
//1 0 [1,2]
//2 1 [1,2]

every方法

定义:测试一个数组内的所有元素是否都能通过某个指定函数的测试(参数与forEach一致)。它返回一个布尔值。

注意: 若收到一个空数组,此方法在一切情况下都会返回 true

const ages = [18, 20, 30];
const result = ages.every(currentValue => currentValue < 40);
console.log(result); // true,因为所有元素都小于40

some方法

定义:方法测试数组中是不是至少有1个元素通过了被提供的函数测试。它返回的是一个Boolean类型的值。

注意: 如果用一个空数组进行测试,在任何情况下它返回的都是false

const ages = [18, 50, 100];
const result = ages.some(currentValue => currentValue < 40);
console.log(result); // true,因为有存在元素是小于40。

reduce方法

定义:对数组中的每个元素执行一个由您提供的reducer函数(升序执行),将其结果汇总为单个返回值。其接收参数如下:

Accumulator:累加器,即元素相加的结果。
currentValue:数组中正在处理的元素。
CurrentIndex:数组中正在处理的元素的索引
SourceArray:源数组。

举例:所有年龄相加。

const ages = [10, 20, 30, 40];
const total = ages.reduce((accumulator,currentValue) => accumulator + currentValue);
console.log(total); // 10+20+30+40=100

举例:可以再拼接其他值相加。

const ages = [10, 20, 30, 40];
const total = ages.reduce((accumulator,currentValue) => accumulator + currentValue, 50); // 结果为原本数组的和,再增加了50
console.log(total); // 10+20+30+40+50=150

这个方法还有一些其他高级的应用场景,我会在如下举例。
举例:累加对象数组里的值(必须提供初始值):

var initialValue = 0;
var sum = [{x: 1},{x: 2},{x: 3}].reduce(
  (acc, cur) => acc + cur.x,
  initialValue
)
console.log(sum) // 6

举例:将二维数组转化为一维

var flattenedd = [[0, 1], [2, 3], [4, 5]].reduce(
  (acc, cur) => arr.concat(cur),
  []
)
console.log(flattenedd)  // [0,1,2,3,4,5]

举例:计算数组中每个元素出现的次数

var names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];
var countedNames = names.reduce(
  (allNames, name) => {
    if(name in allNames) {
      allNames[name]++;
    } else {
      allNames[name] = 1;
    }
  },
  {}
)
console.log(countedNames); // {'Alice': 2, 'Bob': 1, 'Tiff': 1, 'Bruce': 1}

举例:按属性对object分类

var people = [
  { name: 'Alice', age: 21 },
  { name: 'Max', age: 20 },
  { name: 'Jane', age: 20 }
]
const groupBy = (objArr, property) => {
  return objectArray.reduce(
    (acc, obj) => {
      var key = obj[property];
      if(!acc[key]) {
        acc[key] = [];
      }
      acc[key].push(obj)
      return acc;
    },
    {}
  )
}
const groupPeople = groupBy(people, 'age');
console.log(groupPeople)
// {
//   20: [
//     { name: 'Max', age: 20 },
//     { name: 'Jane', age: 20 }
//   ],
//   21: [{ name: 'Alice', age: 21 }]
// }