当前位置:网站首页>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
边栏推荐
- 深度学习笔记 —— 数据增广
- Day. JS common methods
- Mac enters MySQL terminal command
- The applet calls the function of scanning QR code and jumps to the path specified by QR code
- SCP command details
- Uglifyjs compress JS
- 静态流水线和动态流水线的区别认识
- The WebService interface writes and publishes calls to the WebService interface (2)
- Golang memory escape
- This call when the transaction does not take effect
猜你喜欢

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

青岛敏捷之旅,来了!

PIP free export with path (@ file: / / /) notes

At pgconf Asia Chinese technology forum, listen to Tencent cloud experts' in-depth understanding of database technology

数字化转型失败,有哪些原因?

Live delivery form template - automatically display pictures - automatically associate series products

JS engine loop mechanism: synchronous, asynchronous, event loop

The 8 diagrams let you see the execution sequence of async / await and promise step by step

The 2021 more reading report was released, and the book consumption potential of post-95 and Post-00 rose

Data security has become a hidden danger. Let's see how vivo can make "user data" armor again
随机推荐
Detailed explanation of hregionserver
改进DevSecOps框架的 5 大关键技术
Golang select priority execution
The applet calls the function of scanning QR code and jumps to the path specified by QR code
Some experience in using MySQL / tidb database [slowly updating...]
The 2021 more reading report was released, and the book consumption potential of post-95 and Post-00 rose
C language hash dictionary and notes
学习笔记:Unity CustomSRP-10-Point and Spot Shadows
C. Tree Infection(模拟+贪心)
Redis data type usage scenario
使用zerotier让异地设备组局域网
Traversal of tree
Swing display time (click once to display once)
Routing parameters
低代码和无代码的注意事项
One month countdown, pgconf What are the highlights of the latest outlook of asia2021 Asian Conference?
Deep learning notes - object detection and dataset + anchor box
The 8 diagrams let you see the execution sequence of async / await and promise step by step
HRegionServer的详解
【openh264】cmake: msopenh264-static