当前位置:网站首页>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
length
Property 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
边栏推荐
- This call when the transaction does not take effect
- Knowledge points sorting: ES6
- The applet calls the function of scanning QR code and jumps to the path specified by QR code
- 看板快速启动指南
- Summary of MySQL knowledge points
- Redis data type usage scenario
- Detailed explanation of hregionserver
- 【openh264】cmake: msopenh264-static
- Deep learning notes - data expansion
- 5 minutes to understand MySQL row column conversion
猜你喜欢
Deep learning notes - semantic segmentation and data sets
Servlet3 0 + event driven for high performance long polling
[database] MySQL multi table query (I)
mariadb数据库的主从复制
SQLyog的基本使用
Routing parameters
MySQL basics 3
Deep learning notes - fine tuning
MySQL slow query
The WebService interface writes and publishes calls to the WebService interface (I)
随机推荐
使用 Kears 实现ResNet-34 CNN
Streamexecutionenvironment of Flink source code
MySQL external connection, internal connection, self connection, natural connection, cross connection
Traversal of tree
学习笔记:Unity CustomSRP-10-Point and Spot Shadows
Detailed explanation of hregionserver
Deep learning notes - semantic segmentation and data sets
静态流水线和动态流水线的区别认识
C. Tree Infection(模拟+贪心)
Restful toolkit of idea plug-in
Define defines constants and macros, pointers and structures
Locks and transactions in MySQL
何时适合进行自动化测试?(下)
C language hash dictionary and notes
JSP-----JSP简介
Cross border e-commerce | Facebook and instagram: which social media is more suitable for you?
scp命令详解
Routing parameters
JS engine loop mechanism: synchronous, asynchronous, event loop
Barcode generation and decoding, QR code generation and decoding