当前位置:网站首页>JS array common methods
JS array common methods
2022-04-23 05:16:00 【sereposika】
Array.entries()
entries() Method returns a new one Array Iterator object , This object contains the key for each index in the array / It's worth it .
Generate iteratable objects , Use next() Method , use ,done Property as a loop condition
const array1 = ['a', 'b', 'c'];
const iterator1 = array1.entries();
console.log(iterator1.next().value);
// expected output: Array [0, "a"]
console.log(iterator1.next().value);
// expected output: Array [1, "b"]
var arr = ["a", "b", "c"];
var iterator = arr.entries();
// undefined
for (let e of iterator) {
console.log(e);
}
// [0, "a"]
// [1, "b"]
// [2, "c"]
// Traversal of two dimensional array
function sortArr(arr) {
var goNext = true;
var entries = arr.entries();
while (goNext) {
var result = entries.next();
if (result.done !== true) {
result.value[1].sort((a, b) => a - b);
goNext = true;
} else {
goNext = false;
}
}
return arr;
}
var arr = [[1,34],[456,2,3,44,234],[4567,1,4,5,6],[34,78,23,1]];
sortArr(arr);
/*(4) [Array(2), Array(5), Array(5), Array(4)]
0:(2) [1, 34]
1:(5) [2, 3, 44, 234, 456]
2:(5) [1, 4, 5, 6, 4567]
3:(4) [1, 23, 34, 78]
length:4
__proto__:Array(0)
*/
Array.prototype.filter()
filter() Method to create a new array , It contains all the elements of the test implemented by the provided function .
Filter array , Pass the value satisfying the condition into a new array .

Filter out invalid data in the array
var arr = [
{ id: 15 },
{ id: -1 },
{ id: 0 },
{ id: 3 },
{ id: 12.2 },
{ },
{ id: null },
{ id: NaN },
{ id: 'undefined' }
];
var invalidEntries = 0;
function isNumber(obj) {
return obj !== undefined && typeof(obj) === 'number' && !isNaN(obj);
}
function filterByID(item) {
if (isNumber(item.id) && item.id !== 0) {
return true;
}
invalidEntries++;
return false;
}
var arrByID = arr.filter(filterByID);
console.log('Filtered Array\n', arrByID);
// Filtered Array
// [{ id: 15 }, { id: -1 }, { id: 3 }, { id: 12.2 }]
Array.from()
Array.from() Method to create a new... For a similar array or iteratable object , Array instance of shallow copy
**Array.from()** Method to create a new... For a similar array or iteratable object , Array instance of shallow copy .
Array.from() You can create an array object in the following ways :
-
Pseudo array object ( To have a
lengthProperty and several index properties of any object ) -
Iteratable object ( You can get the elements in the object , Such as Map and Set etc. )

// take set Turn into Array
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// [ "foo", "bar", "baz" ]
// take map Convert to array structure
const map = new Map([[1, 2], [2, 4], [4, 8]]);
Array.from(map);
// [[1, 2], [2, 4], [4, 8]]
const mapper = new Map([['1', 'a'], ['2', 'b']]);
Array.from(mapper.values());
// ['a', 'b'];
Array.from(mapper.keys());
// ['1', '2'];
// Handling incoming and outgoing arguments
function f() {
return Array.from(arguments);
}
f(1, 2, 3);
// [ 1, 2, 3 ]
Sequence generation
const range = (start, stop, step) => Array.from({ length: (stop - start) / step + 1}, (_, i) => start + (i * step));
// Generate numbers range 0..4
range(0, 4, 1);
// [0, 1, 2, 3, 4]
// Generate numbers range 1..10 with step of 2
range(1, 10, 2);
// [1, 3, 5, 7, 9]
Array.join()
join() Method puts an array ( Or a Class array object ) Join all the elements of to a string and return the string . If the array has only one entry , Then the item is returned without the separator .
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
Array.map()
map() Method to create a new array , This new array consists of the return value of each element in the original array after calling the provided function once .
var kvArray = [{key: 1, value: 10},
{key: 2, value: 20},
{key: 3, value: 30}];
var reformattedArray = kvArray.map(function(obj) {
var rObj = {};
rObj[obj.key] = obj.value;
return rObj;
});
Array.prototype.slice()
slice() Method returns a new array object , This object is made up of begin and end Determine the original array of Shallow copy ( Include begin, barring end). The original array will not be changed .
var fruits = ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango'];
var citrus = fruits.slice(1, 3);
// fruits contains ['Banana', 'Orange', 'Lemon', 'Apple', 'Mango']
// citrus contains ['Orange','Lemon']
Array.prototype.flat()
flat() Method recursively traverses the array at a specified depth , And all the elements and the elements in the traversed sub array are merged into a new array to return .

Flatten nested arrays
var arr1 = [1, 2, [3, 4]];
arr1.flat();
// [1, 2, 3, 4]
var arr2 = [1, 2, [3, 4, [5, 6]]];
arr2.flat();
// [1, 2, 3, 4, [5, 6]]
var arr3 = [1, 2, [3, 4, [5, 6]]];
arr3.flat(2);
// [1, 2, 3, 4, 5, 6]
// Use Infinity, Can expand any depth of nested array
var arr4 = [1, 2, [3, 4, [5, 6, [7, 8, [9, 10]]]]];
arr4.flat(Infinity);
// [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
// Use reduce、concat And recursively expand infinite multi-layer nested arrays
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatDeep(arr, d = 1) {
return d > 0 ? arr.reduce((acc, val) => acc.concat(Array.isArray(val) ? flatDeep(val, d - 1) : val), [])
: arr.slice();
};
flatDeep(arr1, Infinity);
// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
Using stack stack
// No recursive array flattening , Using stack
// Be careful : Depth control is inefficient , Because you need to check the depth of each value
// Or maybe shift / unshift on w/o reverse , But the end array OPs faster
var arr1 = [1,2,3,[1,2,3,4, [2,3,4]]];
function flatten(input) {
const stack = [...input];
const res = [];
while (stack.length) {
// Use pop from stack Take out and remove the value
const next = stack.pop();
if (Array.isArray(next)) {
// Use push Send back the elements in the inner array , The original input will not be changed
stack.push(...next);
} else {
res.push(next);
}
}
// Reverse the order of restoring the original array
return res.reverse();
}
flatten(arr1);// [1, 2, 3, 1, 2, 3, 4, 2, 3, 4]
版权声明
本文为[sereposika]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/04/202204230510394970.html
边栏推荐
- The 2021 more reading report was released, and the book consumption potential of post-95 and Post-00 rose
- Unity C# 网络学习(四)
- Grpc long connection keepalive
- 【openh264】cmake: msopenh264-static
- 看板快速启动指南
- On distributed lock
- Chapter II project scope management of information system project manager summary
- SCP command details
- 2021-09-23
- Mariadb的半同步复制
猜你喜欢

2022年最热门的招聘技术技能是什么,您绝对想不到

Flip coin (Blue Bridge Cup)

2022/4/22

My old programmer's perception of the dangers and opportunities of the times?

The applet calls the function of scanning QR code and jumps to the path specified by QR code

改进DevSecOps框架的 5 大关键技术

SQLyog的基本使用

深度学习笔记 —— 语义分割和数据集

4 个最常见的自动化测试挑战及应对措施

JS engine loop mechanism: synchronous, asynchronous, event loop
随机推荐
Chapter II project scope management of information system project manager summary
Publish your own wheel - pypi packaging upload practice
我这位老程序员对时代危险和机遇的一点感悟?
Transaction isolation level of MySQL transactions
What are the redis data types
Docker installation and mysql5 7 installation
何时适合进行自动化测试?(下)
Power consumption parameters of Jinbei household mute box series
2022/4/22
静态流水线和动态流水线的区别认识
Pandas to_ SQL function pit avoidance guide "with correct code to run"
Barcode generation and decoding, QR code generation and decoding
JS Array常见方法
Summary of MySQL knowledge points
源码剖析Redis中如何使用跳表的
QPushButton slot function is triggered multiple times
如何在Word中添加漂亮的代码块 | 很全的方法整理和比较
Asynchronous iterator & asynchronous generator & asynchronous context manager
Some experience in using MySQL / tidb database [slowly updating...]
深度学习笔记 —— 数据增广