阿里云主机折上折
  • 微信号
您当前的位置:网站首页 > 数组转换方法

数组转换方法

作者:陈川 阅读数:51424人阅读 分类: JavaScript

数组转换方法

数组是JavaScript中最常用的数据结构之一,提供了多种转换方法。这些方法能够改变数组的结构或内容,生成新的数组或直接修改原数组。

map()方法

map()方法创建一个新数组,其结果是该数组中的每个元素调用一次提供的函数后的返回值。它不会改变原数组。

const numbers = [1, 2, 3];
const doubled = numbers.map(num => num * 2);
console.log(doubled); // [2, 4, 6]

map()接收三个参数:当前元素、当前索引和原数组。可以用于提取对象数组中的特定属性:

const users = [
  { id: 1, name: 'Alice' },
  { id: 2, name: 'Bob' }
];
const names = users.map(user => user.name);
console.log(names); // ['Alice', 'Bob']

filter()方法

filter()方法创建一个新数组,包含通过所提供函数测试的所有元素。

const numbers = [1, 2, 3, 4, 5];
const evens = numbers.filter(num => num % 2 === 0);
console.log(evens); // [2, 4]

可以结合索引参数实现更复杂的过滤:

const words = ['spray', 'limit', 'elite', 'exuberant', 'destruction'];
const longWords = words.filter((word, index) => {
  return word.length > 6 && index % 2 === 0;
});
console.log(longWords); // ['exuberant']

reduce()方法

reduce()方法对数组中的每个元素执行一个reducer函数,将其结果汇总为单个返回值。

const numbers = [1, 2, 3, 4];
const sum = numbers.reduce((accumulator, currentValue) => {
  return accumulator + currentValue;
}, 0);
console.log(sum); // 10

可以实现更复杂的聚合操作:

const orders = [
  { product: 'apple', price: 10, quantity: 2 },
  { product: 'banana', price: 5, quantity: 3 },
  { product: 'orange', price: 8, quantity: 1 }
];
const total = orders.reduce((sum, order) => {
  return sum + (order.price * order.quantity);
}, 0);
console.log(total); // 43

flat()和flatMap()

flat()方法会按照一个可指定的深度递归遍历数组,并将所有元素与遍历到的子数组中的元素合并为一个新数组返回。

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

flatMap()方法首先使用映射函数映射每个元素,然后将结果压缩成一个新数组。

const phrases = ["hello world", "goodbye moon"];
const words = phrases.flatMap(phrase => phrase.split(' '));
console.log(words); // ["hello", "world", "goodbye", "moon"]

sort()方法

sort()方法对数组的元素进行排序,并返回数组。默认排序顺序是根据字符串Unicode码点。

const fruits = ['banana', 'apple', 'orange'];
fruits.sort();
console.log(fruits); // ['apple', 'banana', 'orange']

对于数字排序需要提供比较函数:

const numbers = [10, 2, 5, 1];
numbers.sort((a, b) => a - b);
console.log(numbers); // [1, 2, 5, 10]

Array.from()方法

Array.from()方法从一个类似数组或可迭代对象创建一个新的数组实例。

const str = 'hello';
const chars = Array.from(str);
console.log(chars); // ['h', 'e', 'l', 'l', 'o']

可以结合映射函数使用:

const numbers = Array.from({ length: 5 }, (_, i) => i * 2);
console.log(numbers); // [0, 2, 4, 6, 8]

扩展运算符

扩展运算符...可以将可迭代对象展开到新数组中。

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // [1, 2, 3, 4, 5, 6]

可以用于浅拷贝数组:

const original = [1, 2, 3];
const copy = [...original];
console.log(copy); // [1, 2, 3]

数组与字符串转换

join()方法将数组中的所有元素连接成一个字符串。

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

split()方法将字符串分割成数组:

const str = 'The quick brown fox';
const words = str.split(' ');
console.log(words); // ["The", "quick", "brown", "fox"]

数组去重

使用Set和扩展运算符可以快速实现数组去重:

const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = [...new Set(numbers)];
console.log(unique); // [1, 2, 3, 4, 5]

也可以使用filter()实现:

const numbers = [1, 2, 2, 3, 4, 4, 5];
const unique = numbers.filter((item, index) => {
  return numbers.indexOf(item) === index;
});
console.log(unique); // [1, 2, 3, 4, 5]

数组分组

使用reduce()可以实现数组分组:

const people = [
  { name: 'Alice', age: 21 },
  { name: 'Bob', age: 20 },
  { name: 'Charlie', age: 21 }
];

const groupedByAge = people.reduce((acc, person) => {
  const age = person.age;
  if (!acc[age]) {
    acc[age] = [];
  }
  acc[age].push(person);
  return acc;
}, {});

console.log(groupedByAge);
/*
{
  "20": [{ name: 'Bob', age: 20 }],
  "21": [
    { name: 'Alice', age: 21 },
    { name: 'Charlie', age: 21 }
  ]
}
*/

数组与对象转换

将数组转换为对象:

const entries = [['name', 'Alice'], ['age', 25]];
const obj = Object.fromEntries(entries);
console.log(obj); // { name: 'Alice', age: 25 }

将对象转换为数组:

const obj = { name: 'Alice', age: 25 };
const entries = Object.entries(obj);
console.log(entries); // [['name', 'Alice'], ['age', 25]]

数组填充

fill()方法用一个固定值填充一个数组中从起始索引到终止索引内的全部元素。

const arr = [1, 2, 3, 4];
arr.fill(0, 1, 3);
console.log(arr); // [1, 0, 0, 4]

数组切片

slice()方法返回一个新的数组对象,这一对象是一个由beginend决定的原数组的浅拷贝。

const animals = ['ant', 'bison', 'camel', 'duck', 'elephant'];
console.log(animals.slice(2)); // ["camel", "duck", "elephant"]
console.log(animals.slice(2, 4)); // ["camel", "duck"]

数组查找转换

find()findIndex()方法可以查找数组元素:

const inventory = [
  {name: 'apples', quantity: 2},
  {name: 'bananas', quantity: 0},
  {name: 'cherries', quantity: 5}
];

const result = inventory.find(item => item.name === 'cherries');
console.log(result); // { name: 'cherries', quantity: 5 }

const index = inventory.findIndex(item => item.quantity === 0);
console.log(index); // 1

数组包含检查

includes()方法判断一个数组是否包含一个指定的值:

const array = [1, 2, 3];
console.log(array.includes(2)); // true
console.log(array.includes(4)); // false

数组拼接

concat()方法用于合并两个或多个数组:

const array1 = ['a', 'b', 'c'];
const array2 = ['d', 'e', 'f'];
const array3 = array1.concat(array2);
console.log(array3); // ["a", "b", "c", "d", "e", "f"]

数组反转

reverse()方法将数组中元素的位置颠倒:

const array = [1, 2, 3];
console.log(array.reverse()); // [3, 2, 1]

数组扁平化

除了flat()方法,还可以使用递归实现深度扁平化:

function flattenDeep(arr) {
  return arr.reduce((acc, val) => 
    Array.isArray(val) ? acc.concat(flattenDeep(val)) : acc.concat(val), []);
}

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

数组交集、并集和差集

实现数组的交集、并集和差集:

const arr1 = [1, 2, 3, 4];
const arr2 = [3, 4, 5, 6];

// 并集
const union = [...new Set([...arr1, ...arr2])];
console.log(union); // [1, 2, 3, 4, 5, 6]

// 交集
const intersection = arr1.filter(x => arr2.includes(x));
console.log(intersection); // [3, 4]

// 差集 (arr1有而arr2没有)
const difference = arr1.filter(x => !arr2.includes(x));
console.log(difference); // [1, 2]

数组分块

将数组分割成指定大小的块:

function chunkArray(arr, size) {
  const result = [];
  for (let i = 0; i < arr.length; i += size) {
    result.push(arr.slice(i, i + size));
  }
  return result;
}

const array = [1, 2, 3, 4, 5, 6, 7];
console.log(chunkArray(array, 3)); // [[1, 2, 3], [4, 5, 6], [7]]

数组随机排序

实现数组的随机排序:

function shuffleArray(array) {
  const newArray = [...array];
  for (let i = newArray.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [newArray[i], newArray[j]] = [newArray[j], newArray[i]];
  }
  return newArray;
}

const numbers = [1, 2, 3, 4, 5];
console.log(shuffleArray(numbers)); // 每次结果不同,如[3, 1, 5, 2, 4]

数组元素统计

统计数组中各元素出现的次数:

const fruits = ['apple', 'banana', 'apple', 'orange', 'banana', 'apple'];

const count = fruits.reduce((acc, fruit) => {
  acc[fruit] = (acc[fruit] || 0) + 1;
  return acc;
}, {});

console.log(count); // { apple: 3, banana: 2, orange: 1 }

数组最大值和最小值

不使用Math.max/Math.min找出数组中的最大值和最小值:

const numbers = [5, 2, 9, 1, 7];

const max = numbers.reduce((a, b) => a > b ? a : b);
const min = numbers.reduce((a, b) => a < b ? a : b);

console.log(max); // 9
console.log(min); // 1

数组元素替换

替换数组中特定条件的元素:

const numbers = [1, 2, 3, 4, 5];
const replaced = numbers.map(num => num % 2 === 0 ? 0 : num);
console.log(replaced); // [1, 0, 3, 0, 5]

数组元素移动

将数组元素从一个位置移动到另一个位置:

function moveElement(array, fromIndex, toIndex) {
  const newArray = [...array];
  const element = newArray.splice(fromIndex, 1)[0];
  newArray.splice(toIndex, 0, element);
  return newArray;
}

const numbers = [1, 2, 3, 4, 5];
console.log(moveElement(numbers, 2, 0)); // [3, 1, 2, 4, 5]

数组元素交换

交换数组中两个元素的位置:

function swapElements(array, index1, index2) {
  const newArray = [...array];
  [newArray[index1], newArray[index2]] = [newArray[index2], newArray[index1]];
  return newArray;
}

const letters = ['a', 'b', 'c', 'd'];
console.log(swapElements(letters, 1, 3)); // ['a', 'd', 'c', 'b']

数组元素插入

在数组特定位置插入元素:

function insertElement(array, index, element) {
  const newArray = [...array];
  newArray.splice(index, 0, element);
  return newArray;
}

const colors = ['red', 'green', 'blue'];
console.log(insertElement(colors, 1, 'yellow')); // ['red', 'yellow', 'green', 'blue']

数组元素删除

删除数组中特定条件的元素:

const numbers = [1, 2, 3, 4, 5, 6];
const filtered = numbers.filter(num => num % 2 !== 0);
console.log(filtered); // [1, 3, 5]

数组元素更新

更新数组中特定条件的元素:

const products = [
  { id: 1, name: 'Laptop', price: 1000 },
  { id: 2, name: 'Phone', price: 500 },
  { id: 3, name: 'Tablet', price: 300 }
];

const updated = products.map(product => 
  product.id === 2 ? { ...product, price: 450 } : product
);

console.log(updated);
/*
[
  { id: 1, name: 'Laptop', price: 1000 },
  { id: 2, name: 'Phone', price: 450 },
  { id: 3, name: 'Tablet', price: 300 }
]
*/

数组元素提取

从数组中提取满足条件的元素:

const users = [
  { id: 1, name: 'Alice', active: true },
  { id: 2, name: 'Bob', active: false },
  { id: 3, name: 'Charlie', active: true }
];

const activeUsers = users.filter(user => user.active);
console.log(activeUsers);
/*
[
  { id: 1, name: 'Alice', active: true },
  { id: 3, name: 'Charlie', active: true }
]
*/

数组元素分组计数

对数组元素进行分组并计数:

const votes = ['yes', 'no', 'yes', 'yes', 'no', 'abstain'];

const result = votes.reduce((acc, vote) => {
  acc[vote] = (acc[vote] || 0) + 1;
  return acc;
}, {});

console.log(result); // { yes: 3, no: 2, abstain: 1 }

数组元素去重并排序

对数组元素去重并排序:

const numbers = [3, 1, 2, 3, 4, 2, 5, 1];
const uniqueSorted = [...new Set(numbers)].sort((a, b) => a - b);
console.log(uniqueSorted); // [1, 2, 3, 4, 5]

数组元素映射转换

对数组元素进行复杂映射转换:

const temperatures = [
  { city: 'New York', temp: 22 },
  { city: 'London', temp: 18 },
  { city: 'Tokyo', temp: 25 }
];

const formatted = temperatures.map(({ city, temp }) => {
  return {
    location: city.toUpperCase(),
    temperature: `${temp}°C`,
    isWarm: temp > 20
  };
});

console.log(formatted);
/*
[
  { location: 'NEW YORK', temperature: '22°C', isWarm: true },
  { location: 'LONDON', temperature: '18°C', isWarm: false },
  { location: 'TOKYO', temperature: '25°C', isWarm: true }
]
*/

本站部分内容来自互联网,一切版权均归源网站或源作者所有。

如果侵犯了你的权益请来信告知我们删除。邮箱:cc@cccx.cn

上一篇:表单元素操作

下一篇:数组迭代方法

前端川

前端川,陈川的代码茶馆🍵,专治各种不服的Bug退散符💻,日常贩卖秃头警告级的开发心得🛠️,附赠一行代码笑十年的摸鱼宝典🐟,偶尔掉落咖啡杯里泡开的像素级浪漫☕。‌