This is the 12th day of my participation in Gwen Challenge
Some common Array Array functions
An array of
Array to heavy
The object array
- The map method
function unique(arr,u_key) {
let map = new Map()
arr.forEach((item,index) = >{
if(! map.has(item[u_key])){ map.set(item[u_key],item) } })return [...map.values()];
};
Copy the code
- The reduce method
let arrayUniqueObject = (arr, name) = > {
var hash = {};
return arr.reduce(function (item, next) {
if(! next)return ;
hash[next[name]] ? ' ' : hash[next[name]] = true && item.push(next);
returnitem; } []); }Copy the code
Regular array
- Es6 set method
function noRepeat(arr) {
return [...new Set(arr)]
}
Copy the code
- Map data structure deduplication
function unique(arr){
return arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cur],[]);
}
Copy the code
- reduce+includes
function unique(arr){
return arr.reduce((prev,cur) = > prev.includes(cur) ? prev : [...prev,cur],[]);
}
Copy the code
- HasOwnProperty to heavy
function unique(arr) {
var obj = {};
return arr.filter(function(item, index, arr){
return obj.hasOwnProperty(typeof item + item) ? false : (obj[typeof item + item] = true)})Copy the code
- Includes to heavy
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error! ')
return
}
var array =[];
for(var i = 0; i < arr.length; i++) {
if( !array.includes( arr[i]) ) {//includes checks whether the array has a valuearray.push(arr[i]); }}return array
}
Copy the code
- Sorting adjacent division
function unique(arr) {
if (!Array.isArray(arr)) {
console.log('type error! ')
return
}
var array =[];
for(var i = 0; i < arr.length; i++) {
if( !array.includes( arr[i]) ) {//includes checks whether the array has a valuearray.push(arr[i]); }}return array
}
Copy the code
Find array Max
function arrayMax(arr) {
return Math.max(... arr); }Copy the code
Find the smallest array
function arrayMin(arr) {
return Math.min(... arr); }Copy the code
Returns an array split with size as length
function chunk(arr, size = 1) {
return Array.from({
length: Math.ceil(arr.length / size)
}, (v, i) = > arr.slice(i * size, i * size + size));
}
Copy the code
Checks the number of occurrences of an element in an array
function countOccurrences(arr, value) {
return arr.reduce((a, v) = > v === value ? a + 1 : a + 0.0);
}
Copy the code
Flattening an array
- By default, all depth is expanded
function flatten(arr, depth = -1) {
if (depth === -1) {
return[].concat(... arr.map(v= > Array.isArray(v) ? this.flatten(v) : v))
}
if (depth === 1) {
return arr.reduce((a, v) = > a.concat(v), []);
}
return arr.reduce((a, v) = > a.concat(Array.isArray(v) ? this.flatten(v, depth - 1) : v), [])
}
Copy the code
- Extend operator methods
function flatten(arr) {
while(arr.some(item= >Array.isArray(item))) { arr = [].concat(... arr); }return arr;
}
Copy the code
- recursive
function flatten(arr) {
var res = [];
arr.map(item= > {
if(Array.isArray(item)) {
res = res.concat(flatten(item));
} else{ res.push(item); }});return res;
}
Copy the code
- Join & split methods – purely numeric multidimensional arrays
function flatten(arr) {
return arr.join(', ').split(', ').map(function(item) {
return parseInt(item); })}Copy the code
- ToString & Split methods – pure numeric multidimensional arrays
function flatten(arr) {
return arr.toString().split(', ').map(function(item) {
return Number(item); })}Copy the code
- Use Stack to unnest multiple layers of nested arrays indefinitely
function flatten(input) {
const stack = [...input]; // Ensure that the original array is not destroyed
const result = [];
while(stack.length) {
const first = stack.shift();
if(Array.isArray(first)) { stack.unshift(... first); }else{ result.push(first); }}return result;
}
Copy the code
- New method flat(depth) provided by ES6
let a = [1[2.3]];
a.flat(); / / [1, 2, 3]
a.flat(1); / / [1, 2, 3]
Copy the code
The parameter depth in the flat(depth) method, which represents the depth at which the nested array is expanded, defaults to 1
So we can flatten the 2-dimensional array by adding 1, or we can flatten the 2-dimensional array by calling flat(). If we know the dimensions ahead of time, we flatten the array, and depth is the array minus one.
let a = [1[2.3[4[5]]]];
a.flat(4-1); [1,2,3,4,5] a is a 4-dimensional array
Copy the code
There is an even easier way to make the target array a 1-dimensional array without knowing the dimensions. Depth is set to Infinity.
let a = [1[2.3[4[5]]]];
a.flat(Infinity); [1,2,3,4,5] a is a 4-dimensional array
Copy the code
Compare two arrays and return the different elements
function diffrence(arrA, arrB) {
return arrA.filter(v= >! arrB.includes(v)) }Copy the code
Returns the same element in both arrays
function intersection(arr1, arr2) {
return arr2.filter(v= > arr1.includes(v))
}
Copy the code
Remove n elements from the right
function dropRight(arr, n = 0) {
return n < arr.length ? arr.slice(0, arr.length - n) : [];
}
Copy the code
Intercepts the first qualifying element and subsequent elements
function dropElements(arr, fn) {
while(arr.length && ! fn(arr[0])) arr = arr.slice(1);
return arr;
}
Copy the code
Returns the element in the array with the subscript interval NTH
function everyNth(arr, nth) {
return arr.filter((v, i) = > i % nth === nth - 1)}Copy the code
Returns the NTH element of the array
Support negative
function nthElement(arr, n = 0) {
return (n >= 0 ? arr.slice(n, n + 1) : arr.slice(n))[0]}Copy the code
Returns the array header element
function head(arr) {
return arr[0]}Copy the code
Returns the last element of the array
function last(arr) {
return arr[arr.length - 1]}Copy the code
Array random row
function shuffle(arr) {
let array = arr
let index = array.length
while (index) {
index -= 1
let randomInedx = Math.floor(Math.random() * index)
let middleware = array[index]
array[index] = array[randomInedx]
array[randomInedx] = middleware
}
return array
}
Copy the code
Flattening arrays of tree structures (in order)
- cycle
function treeData(arr) {
let cloneData = JSON.parse(JSON.stringify(arr)) // Make a deep copy of the original array to avoid affecting the original data
return cloneData.filter(father= > {
let branchArr = cloneData.filter(child= > father.id == child.parentId);
branchArr.length > 0 ? father.children = branchArr : ' '
return father.parentId == null If the parent id of the highest level is not null, please modify it yourself})}Copy the code
const treeToArray = (data,childKey) = > {
let result = [];
data.forEach(item= > {
if (item[childKey]) {
item[childKey] && treeToArray(item[childKey]);
}
result.push(item);
});
return result;
};
Copy the code