Algorithm array package convenient operation es6

/*
* @Description: the basic operation of the array
* @Author: Shi Zhipeng
* @LastEditors: Please set LastEditors
* @Date: 2019-04-26 12:00:19
* @LastEditTime: 2019-07-17 09:54:59
*/

var $ = require("jquery");

const arrayBase = {};

/**
* @Description: an array of heavy small to large order, returns a new array
* @Param {type} Arr array
* @return:
*/

arrayBase.minToMax = Arr => {
were min;
for (var i = 0; i < Arr.length; i++) {
for (var j = i; j < Arr.length; j++) {
if (Arr[i] > Arr[j]) {
Arr = min [j];
Arr[j] = Arr[i];
Arr [i] = min;
}
}
}
return Arr;
};

/**
* @Description: Array easiest way to duplicate
* @Param {type} arr Type: Array
* @return:
*/

arrayBase.formatDedupeArr = arr => [...new Set(arr)];

/**
* @Description: calculate the number of occurrences of values ​​in the array.
* @Param {type} arr array
* @param {type} value 值
* @return:
*/
arrayBase.countOccurrences = (arr, value) =>
arr.reduce((a, v) => (v === value ? a + 1 : a + 0), 0);
The results are shown // // countOccurrences ([1,1,2,1,2,3], 1) -> 3

/**
* @Description: Returns the difference between two arrays
* @Param {type} a array a
* @Param {type} b array b
* @return:
*/
arrayBase.difference = (a, b) => {
debugger;
const c = new Set(b);
return a.filter(x => !c.has(x));
};
The results are shown // // difference ([1,2,3], [1,2,4]) -> [3]

/**
* Returns the same value between the two arrays i.e. symmetric difference
* @Description: Creating a Set from each array, and each of them uses Array.filter (), in order to retain only the numerical value is not included in the other.
* @param {type}
* @return:
*/

arrayBase.symmetricDifference = (a, b) => {
const sA = new Set (a),
sB = new Set(b);
return [...a.filter(x => !sB.has(x)), ...b.filter(x => !sA.has(x))];
};
// returns the results and methods of use
// symmetricDifference([1,2,3], [1,2,4]) -> [3,4]

/**
* @Description: returns the same value in the presence of two arrays, namely array and take two values
* @param {type}
* @return:
*/
arrayBase.intersection = (arr1, arr2) => {
const arr3 = new Set(arr2);
return a.filter(x => s.has(x));
};
// results were as follows: intersection ([1,2,3], [4,3,2]) -> [2,3]

// /**
// * @description: removal of elements in the array until the transfer function returns true, return the rest of the array elements
// * @param {type}
// * @return:
// */

/**
* @Description: mosaic array using Array.reduce () Get all elements in the array and concat () to split them.
* @param {type}
* @return:
*/

arrayBase.flatten = arr => arr.reduce((a, v) => a.concat(v), []);
The results are shown // // flatten ([1, [2], 3,4]) -> [1,2,3,4]

/**
* The given function of the array elements are grouped.
* @Description: Use Array.map () array of values ​​is mapped to a function or property name. Use Array.reduce () to create an object, where the key is generated from the result of the mapping.
* @Param {type} arr array
Function or condition * @param {type} func packet
* @return:
*/

arrayBase.groupBy = (arr, func) =>
arr
.map(typeof func === "function" ? func : val => val[func])
.reduce((acc, val, i) => {
acc[val] = (acc[val] || []).concat(arr[i]);
return acc;
}, {});

// results were as follows: // groupBy ([6.1, 4.2, 6.3], Math.floor) -> {4: [4.2], 6: [6.1, 6.3]}
// groupBy(['one', 'two', 'three'], 'length') -> {3: ['one', 'two'], 5: ['three']}

/ * Array of values ​​using a function mapped to an object, wherein the composition from the original key value as a key value and mapping.
* @Description: using anonymous inner radius to function declarations undefined memory space used to store the return value closures. Array can use the new function and the mapping array on which a data set,
* Comma operator returns the second step, without the need to move from one environment to another context to (and since the closing operation sequence).
* @Param {type} arr array
* @Param {type} fu function
* @return:
*/

arrayBase.mapObject = (arr, fn) =>
(a => (
(a = [arr, arr.map(fn)]),
a[0].reduce((acc, val, ind) => ((acc[val] = a[1][ind]), acc), {})
))();
// results are as follows:
// let squareIt = arr => mapObject(arr, a => a*a)
// squareIt([1,2,3]) // { 1: 1, 2: 4, 3: 9 }

/ * Array of variation, to filter out the specified value.
* @Description: Use Array.filter () and Array.includes () to pull out unwanted values. Use Array.length = 0 can be passed in the array length is reset to zero,
* And set Array.push (), so as to fill it uses only the extracted values.
* @Param {type} arr array
* ... args array unwanted values ​​@param {type}, it may be a plurality of
* @return:
*/
arrayBase.pull = (arr, ...args) => {
let pulled = arr.filter((v, i) => !args.includes(v));
arr.length = 0;
pulled.forEach(v => arr.push(v));
};

// results are as follows:
// let myArray = ['a', 'b', 'c', 'a', 'b', 'c'];
// pull(myArray, 'a', 'c');
// console.log(myArray) -> [ 'b', 'b' ]

/**
* Remove from the array to set the function returns false element.
* @Description: Use Array.filter () Find the value of array elements returned truthy and Array.reduce () to use Array.splice () to remove elements.
* Use three-parameter (func value, index, array function call).
* @Param {type} arr array
* @Param {type} func function Custom
* @return:
*/

arrayBase.removeFunction = (arr, func) =>
Array.isArray(arr)
? arr.filter(func).reduce((acc, val) => {
arr.splice(arr.indexOf(val), 1);
return acc.concat(val);
}, [])
: [];
// Returns used as follows:
// remove([1, 2, 3, 4], n => n % 2 == 0) -> [2, 4]

/**
* Returns a random element in the array.
* @Description: generating a random number using Math.random (), it is multiplied with the length,
* And its use of mathematical rounding to the nearest integer Math.floor ().
* Note :::: This method also applies to the strings.
* @param {type}
* @return:
*/

arrayBase.shuffle = arr => arr[Math.floor(Math.random() * arr.length)];
// Returns used as follows:
// sample([3, 7, 9, 11]) -> 9

Sequential / random array values ​​**.
* @Description: using the Array.sort () may be used in the comparator Math.random () reordering element.
* @param {type}
* @return:
*/

arrayBase.shuffle = arr => arr.sort(() => Math.random() - 0.5);
// Returns used as follows:
// shuffle([1,2,3]) -> [2,3,1]

/**
* Returns an array of n elements is removed from the beginning.
* @Description: creating an array of slices used Array.slice (), which contains n elements taken from the beginning.
* @Param {type} arr array
* @Param {type} n array index starts in
* @return:
*/

arrayBase.take = (arr, n = 1) => arr.slice(0, n);
// Returns used as follows:
// take([1, 2, 3], 5) -> [1, 2, 3]
// take([1, 2, 3], 0) -> []

/**
* Each element of any one of the two array returned present.
* @Description: Create a Set, which contains all the values ​​of a and b, and converts it into an array.
* @Param {type} a array
* @Param {type} b Array
* @return:
*/

arrayBase.union = (a, b) => Array.from(new Set([...a, ...b]));
// Returns used as follows:
// union([1,2,3], [4,3,2]) -> [1,2,3,4]

/**
* Create original array elements in the array based on the position of the packet.
* @Description: Use Math.max.apply () Gets the parameters in the longest array. Create a return to the length of the array of values,
* And creates a packet using the map function element array Array.from () if the length of the array of different parameters, is used in the case where any undefined value is not found.
*
* @param {type}
* @return:
*/

arrayBase.zip = (...arrays) => {
const maxLength = Math.max(...arrays.map(x => x.length));
return Array.from({ length: maxLength }).map((_, i) => {
return Array.from({ length: arrays.length }, (_, k) => arrays[k][i]);
});
};
// Returns used as follows:
//zip(['a', 'b'], [1, 2], [true, false]); -> [['a', 1, true], ['b', 2, false]]
//zip(['a'], [1, 2], [true, false]); -> [['a', 1, true], [undefined, 2, false]]

/**
* Returns the average digital array.
* @Description: Use Array.reduce () to add value to each accumulator, and initializes a value of 0, divided by the array length.
* @Param {type} arr array of numbers
* @return:
*/

arrayBase.arrayAverage = arr =>
arr.reduce((acc, val) => acc + val, 0) / arr.length;
// arrayAverage([1,2,3]) -> 2

/**
* Returns the sum of a numeric array.
* @Description: Use Array.reduce () to add value to each accumulator, and the value 0 to initialize.
* @param {type}
* @return:
*/

arrayBase.arraySum = arr => arr.reduce((acc, val) => acc + val, 0);
// arraySum([1,2,3,4]) -> 10

/**
* Converts a number to an array of numbers
* @Description: converts a number to a string, using extended operator builds array ES6 ([... string]) in. Use Array.map () and the parseInt () converts each integer value.
* @param {type}
* @return:
*/

arrayBase.digitize = n => [...("" + n)].map(i => parseInt(i));
// digitize(2334) -> [2, 3, 3, 4]

/**
* Returns the value of the digital intermediate array.
* @Description: find the middle of the array, using the Array.sort () to rank value. If the length is odd, the digital midpoint is returned, otherwise the average of two intermediate numbers.
* @param {type}
* @return:
*/

arrayBase.median = arr => {
const mid = Math.floor(arr.length / 2),
nums = arr.sort((a, b) => a - b);
return arr.length % 2 !== 0 ? nums[mid] : (nums[mid - 1] + nums[mid]) / 2;
};
// median([5,6,50,1,-5]) -> 5
// median([0,10,-2,7]) -> 3.5

/**
* Calculate the maximum common divisor between two numbers.
* @Description: use recursion. The basic case is when y is equal to 0. In this case, return x. Otherwise, GCD and returns the remainder of the division of y x / y.
* @param {type}
* @return:
*/

arrayBase.gcd = (x, y) =>:; (x and gcd (y, x% y)!?)
// gcd (8, 36) -> 4

/**
* Returns a random integer within the specified range.
* @Description: Use Math.random () generates a random number and maps it to the desired range using Math.floor () to become an integer.
* @param {type}
* @return:
*/

arrayBase.randomIntegerInRange = (min, max) =>
Math.floor(Math.random() * (max - min + 1)) + min;
// randomIntegerInRange(0, 5) -> 2

/**
* Rounds a number to the specified number of places.
* @Description: Use Math.round () and template text round numbers to the specified number of digits. The second argument is omitted, decimals rounded to an integer.
* @param {type}
* @return:
*/

arrayBase.round = (n, decimals = 0) =>
Number(`${Math.round(`${n}e${decimals}`)}e-${decimals}`);
// round(1.005, 2) -> 1.01

/**
* To retrieve an array of objects, and returns a new array of objects
* @description:
* @Param arr an array of filters
* @Param value value retrieved
* @Param key array of objects retrieved key
* @return:
*/
arrayBase.filterArrayObject = (arr, value, key) =>
arr.filter(item => item[key].indexOf(value) > -1);

/**
* To retrieve an array of objects, and returns a new array of objects
* @description:
* @Param arr an array of filters
* @Param value value retrieved
* @Param key array of objects retrieved key
* @return:
*/
arrayBase.byKyeArray = (arr, key) =>
arr
.map(v => {
return v[key];
})
.join();

// results are as follows:
// arr= [{a:1,b:0},{a:2,b:3}]
// filterArrayObject (arr, a) Results [1,2];

/**
* Two arrays is determined whether or not the same, the order does not matter, return ture
* @description:
* @Param listA, listB array
* @return:
*/

arrayBase.compareArray = (listA, listB) => {
// Remember that the two arrays, is not the case, all returns false. Plus a determination, the verification is
if (listA instanceof Array && listB instanceof Array) {
return (
listA.length === listB.length &&
listA.every(a => listB.some(b => a === b)) &&
listB.every(_b => listA.some(_a => _a === _b))
);
} else {
console.log ( "listA input field is not listB or array type");
}
};
// does the list = [1, 2, 3]
//const listB = [2, 3, 1]

/**
* Restructuring array object, and return to the array
* @description:
* @Param property // array of objects of Mo a key
* @return:
*/

// arrayBase.compare (property => (a,b) =>{
// var value1 = a [property];
// var value2 = b[property];
// return value1 - value2;
// })

// console.log(arr.arrayBase.sort(arrayBase.compare('age')))

export default arrayBase;

/**
* @Description: the array of alternative locations, for example at index 0 of the last change to one.
* @Param {type} array array, start start index, end end subscript
* @Return: return to a new array, the array size unchanged.
*/

arrayBase.arrayIndexPsition = (array, start, end) =>
array.splice(start, 1, ...array.splice(end, 1, array[start]));

/**
* @Description: After the first position in the array of deleted appended to the desired location
* @Param {type} array, start position of the deleted index, end position of the additional subscript
* @return:
*/
arrayBase.arrayIndexsplice = (array, start, end) =>
array.splice(start, 1, ...array.splice(end, 0, array[start]));

/**
* @Description: value of an item to sort an array of objects
* @Param {type} attr sort attributes for the array object number as the key attributes
* @Param {type} rev true indicates ascending, false descending order
* @return:
*/
arrayBase.sortBy = (attr, rev) => {
if (rev == undefined) {
rev = 1;
} else {
rev = rev ? 1 : -1;
}
return (a, b) => {
a = a[attr];
b = b[attr];
if (a < b) {
return rev * -1;
}
if (a > b) {
return rev * 1;
}
return 0;
};
};

/**
* @Description: remove falsey value from the array. Use Array.filter () falsey selected value (false, null, 0, "", undefined and NaN).
* @param {type}
* @return:
*/
arrayBase.compact = arr => arr.filter(Boolean);
//// compact([0, 1, false, 2, '', 3, 'a', 'e'*23, NaN, 's', 34]) -> [ 1, 2, 3, 'a', 's', 34 ]

/**
* @Description: screen out non-unique values ​​in the array to array contains only unique values, use Array.filter ().
* @param {type}
* @return:
*/
arrayBase.filterNonUnique = arr =>
arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
// filterNonUnique([1,2,2,3,4,4,5]) -> [1,3,5]

Guess you like

Origin www.cnblogs.com/sunliyuan/p/11274502.html