javascript 阵列methods.js

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了javascript 阵列methods.js相关的知识,希望对你有一定的参考价值。

1. Remove duplicates from an array of numbers/strings
Well, this is the only one not about map/reduce/filter but it’s so concise that it was hard not to put it in the list. Plus we’ll use it in a couple of examples too.
let values = [3, 1, 3, 5, 2, 4, 4, 4];
let uniqueValues = [...new Set(values)];
// uniqueValues is [3, 1, 5, 2, 4]
2. A simple search (case-sensitive)
The .filter() method creates a new array with all elements that pass the test implemented by the provided function.
let users = [
  { id: 11, name: 'Adam', age: 23, group: 'editor' },
  { id: 47, name: 'John', age: 28, group: 'admin' },
  { id: 85, name: 'William', age: 34, group: 'editor' },
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
];what is 
// res is []
3. A simple search (case-insensitive)
let res = users.filter(it => new RegExp('oli', "i").test(it.name));
// res is
[
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
]
4. Check if any of the users have admin rights
The .some() method tests whether at least one element in the array passes the test implemented by the provided function.
let hasAdmin = users.some(user => user.group === 'admin');
// hasAdmin is true
5. Flattening an array of arrays
The result of the first iteration is equal to : […[], …[1, 2, 3]] means it transforms to [1, 2, 3] — this value we provide as an ‘acc’ on the second iteration and so on.
let nested = [[1, 2, 3], [4, 5, 6], [7, 8, 9]];
let flat = nested.reduce((acc, it) => [...acc, ...it], []);
// flat is [1, 2, 3, 4, 5, 6, 7, 8, 9]
Probably this is the shortest implementation for flattering an array (build in Array.flat is still an experimental feature). Note that using the spread operatorinside reduce is not great for performance. This is a case when measuring performance makes sense for your use-case ☝️.
6. Create an object that contains the frequency of the specified key
Let’s group and count ‘age’ property for each item in the array:
let users = [
  { id: 11, name: 'Adam', age: 23, group: 'editor' },
  { id: 47, name: 'John', age: 28, group: 'admin' },
  { id: 85, name: 'William', age: 34, group: 'editor' },
  { id: 97, name: 'Oliver', age: 28, group: 'admin' }
];
let groupByAge = users.reduce((acc, it) =>
  ({ ...acc, [it.age]: (acc[it.age] || 0) + 1 }),
{});
// groupByAge is {23: 1, 28: 2, 34: 1}
7. Indexing an array of objects (lookup table)
Instead of processing the whole array for finding a user by id we can construct an object where user’s id will be set as a key (with constant searching time).
let uTable = users.reduce((acc, it) => ({...acc, [it.id]: it }), {})
// uTable equals:
{
  11: { id: 11, name: 'Adam', age: 23, group: 'editor' },
  47: { id: 47, name: 'John', age: 28, group: 'admin' },
  85: { id: 85, name: 'William', age: 34, group: 'editor' },
  97: { id: 97, name: 'Oliver', age: 28, group: 'admin' }
}
It’s useful when you have to access our data by id like uTable[85].name a lot.
8. Extract the unique values for the given key of each item in the array
Let’s create a list of existing users’ groups.
let listOfUserGroups = [...new Set(users.map(it => it.group))];
// listOfUserGroups is now ['editor', 'admin'];
9. Object key-value map reversal
let cities = {
  Lyon: 'France',
  Berlin: 'Germany',
  Paris: 'France'
};
let countries = Object.keys(cities).reduce(
  (acc, k) => (acc[cities[k]] = [...(acc[cities[k]] || []), k], acc) , {});
// countries is
{
  France: ["Lyon", "Paris"],
  Germany: ["Berlin"]
}
This one-liner looks quite tricky. We use a comma operator here, it means we return the last value in parenthesis — acc. Let’s rewrite this example in a more production-ready way:
let countries = Object.keys(cities).reduce((acc, k) => {
  let city = cities[k];
  acc[city] = [...(acc[city] || []), k];
  return acc;
}, {});
10. Create an array of Fahrenheit values from an array of Celsius values
The .map() method creates a new array with the results of calling a provided function on every element in the calling array.
Think of it as processing each element with a given formula 

以上是关于javascript 阵列methods.js的主要内容,如果未能解决你的问题,请参考以下文章

javascript Uniq阵列

javascript 展平阵列

javascript 阵列的方法

javascript [js- [阵列的API]]

javascript 创建我们自己的阵列

javascript 展平阵列