阿里云主机折上折
  • 微信号
Current Site:Index > Array conversion method

Array conversion method

Author:Chuan Chen 阅读数:51423人阅读 分类: JavaScript

Array Transformation Methods

Arrays are one of the most commonly used data structures in JavaScript, offering various transformation methods. These methods can alter the structure or content of an array, generating new arrays or modifying the original array directly.

map() Method

The map() method creates a new array populated with the results of calling a provided function on every element in the calling array. It does not modify the original array.

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

map() accepts three parameters: the current element, current index, and the original array. It can be used to extract specific properties from an array of objects:

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

filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

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

It can be combined with the index parameter for more complex filtering:

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() Method

The reduce() method executes a reducer function on each element of the array, resulting in a single output value.

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

It can perform more complex aggregation operations:

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() and flatMap()

The flat() method creates a new array with all sub-array elements concatenated into it recursively up to the specified depth.

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]

The flatMap() method first maps each element using a mapping function, then flattens the result into a new array.

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

sort() Method

The sort() method sorts the elements of an array in place and returns the sorted array. The default sort order is based on string Unicode code points.

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

For numerical sorting, a compare function is required:

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

Array.from() Method

The Array.from() method creates a new array instance from an array-like or iterable object.

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

It can be used with a mapping function:

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

Spread Operator

The spread operator ... can expand an iterable object into a new array.

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

It can be used for shallow array copying:

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

Array and String Conversion

The join() method joins all elements of an array into a string.

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

The split() method splits a string into an array:

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

Array Deduplication

Using Set and the spread operator for quick array deduplication:

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

Alternatively, using 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]

Array Grouping

Using reduce() for array grouping:

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 }
  ]
}
*/

Array and Object Conversion

Converting an array to an object:

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

Converting an object to an array:

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

Array Filling

The fill() method fills all elements in an array from a start index to an end index with a static value.

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

Array Slicing

The slice() method returns a shallow copy of a portion of an array into a new array object.

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

Array Search Transformation

The find() and findIndex() methods can search for array elements:

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

Array Inclusion Check

The includes() method determines whether an array includes a certain value:

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

Array Concatenation

The concat() method is used to merge two or more arrays:

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

Array Reversal

The reverse() method reverses an array in place:

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

Array Flattening

Besides the flat() method, recursive flattening can be implemented:

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]

Array Intersection, Union, and Difference

Implementing array intersection, union, and difference:

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

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

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

// Difference (elements in arr1 but not in arr2)
const difference = arr1.filter(x => !arr2.includes(x));
console.log(difference); // [1, 2]

Array Chunking

Splitting an array into chunks of a specified size:

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

Array Shuffling

Implementing random array shuffling:

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)); // Results vary, e.g., [3, 1, 5, 2, 4]

Array Element Counting

Counting occurrences of elements in an array:

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 }

Array Maximum and Minimum

Finding array maximum and minimum without 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

Array Element Replacement

Replacing elements that meet specific conditions:

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]

Array Element Moving

Moving an array element from one position to another:

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]

Array Element Swapping

Swapping positions of two elements in an array:

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']

Array Element Insertion

Inserting an element at a specific position in an array:

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']

Array Element Deletion

Deleting elements that meet specific conditions:

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

Array Element Updating

Updating elements that meet specific conditions:

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 }
]
*/

Array Element Extraction

Extracting elements that meet specific conditions:

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 }
]
*/

Array Element Group Counting

Grouping and counting array elements:

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 }

Array Deduplication and Sorting

Deduplicating and sorting array elements:

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]

Array Element Mapping Transformation

Complex mapping transformations of array elements:

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

上一篇:表单元素操作

下一篇:数组迭代方法

Front End Chuan

Front End Chuan, Chen Chuan's Code Teahouse 🍵, specializing in exorcising all kinds of stubborn bugs 💻. Daily serving baldness-warning-level development insights 🛠️, with a bonus of one-liners that'll make you laugh for ten years 🐟. Occasionally drops pixel-perfect romance brewed in a coffee cup ☕.