What is the

When dealing with array objects in development, there are some problems.

Here’s a note

  1. Problem 1: array duplication
  2. Problem two: array objects to duplicate
  3. Problem three: Array substitution values
  4. Problem 4: Array merge
  5. Problem 5: Arrays delete virtual values
  6. Problem 6: Arrays take random values
  7. Problem 7: Array summation
  8. Problem 8: Array inversion
  9. Problem 9: Array to object
  10. Problem 10: Array objects take specified key values
  11. Problem 11: Array to string
  12. Problem 12: Array merge
  13. Problem 13: Array intersection
  14. Problem 14: Array difference set
  15. Problem 15: Array traversal
  16. Problem 16: Check whether there are values in the array that match the condition
  17. Check whether all elements in an array meet the criteria
  18. Problem 18: Find the first element/subscript that meets the criteria
  19. Problem 19: shallow/deep copy array
  20. Problem 20: Array Max and min values
  21. Problem 21: Array element count
  22. Problem 22: Array element position statistics
  23. Problem 23: Arrays are grouped by elements
  24. Problem 24: Array URL parameter serialization
  25. Problem 25: Deserialization of array URL parameters
  26. Problem 26: Array flat
  27. Problem 27: Array reduce function
  28. Problem 28: Array objects get subscripts
  29. Problem 29: Array recursive tree
  30. Problem 30: Array reduce generates HTML

Return a new array without changing the original array: join concat slice map every some filter forEach reduce

Push pop Shift unshift reverse sort Slice

Problem 1: array duplication

const unique = arr= > arr.filter((element, index, self) = > self.indexOf(element) === index);
Copy the code

Problem two: array objects to duplicate

const arr = [
    { id: 1.name: 'Joe' },
    { id: 2.name: 'bill' },
    { id: 11.name: 'Cathy' },
    { id: 1.name: 'Joe' },
    { id: 11.name: 'Cathy' },
    { id: 3.name: 'bill'}];const unique = (arr, name) = > {
    let cache = [];
    for(let item of arr){
        if(cache.find(v= > v[name] === item[name])) {
            continue;
        }
        cache.push(item);
    }
    return cache;
}

const filterNonUniqueBy = (arr, fn) = >
  arr.filter((val, index) = >
    arr.every((x, y) = > (index === y) === fn(val, x, index, y))
  );

// filterNonUniqueBy(arr,(a, b) => a.id === b.id)
console.log(unique(arr, 'id')); 
/ / / {id: 1, name: "* *"}, {id: 2, name: "bill"}, {id: 11, name: "detective"}, {id: 3, name: "bill"}]
Copy the code

Problem three: Array substitution values

var cache = ['wxh'.'wxh2'.'wxh3'.'wxh4'.'wxh5']
cache.splice(0.2.'wxh'.'wxh')
console.log(cache) // ['wxh','wxh','wxh3','wxh4','wxh5']
Copy the code

Problem 4: Array merge

var array = [1.2.2.3.5.6];
var array2 = [1.2.2.3.5.6];
var cache = [...array,...array2]
Copy the code

Problem 5: Arrays delete virtual values

var array = [1.2.2.3.5.6];
// In JS, virtual values are false, 0, null, NaN, undefined. We can use the.filter() method to filter these virtual values.
var cache = array.filter(Boolean);
Copy the code

Problem 6: Arrays take random values

var array = [1.2.2.3.5.6];
var cache = array[(Math.floor(Math.random() * (array.length)))];
Copy the code

Problem 7: Array summation

var array = [1.2.2.3.5.6];
var cache = array.reduce((x,y) = > x + y);
Copy the code

Problem 8: Array inversion

function Reverse(arr) {
    return arr.reduceRight((item,value) = > (item.push(value),item),[]);
}
//[5, 4, 3, 2, 1]
Copy the code

Problem 9: Array to object

const cache = [1.2.3.4];
constarrayToObject = {... arr};// {0: 1, 1: 2, 2: 3, 3: 4}


const cache = {'name':'wxh'.'title':'hello world'}
const ObjectToArray = Object.getOwnPropertyNames(cache); // ["name", "title"]
const ObjectToArray = Object.keys(cache).map(function(i){return cache[i]}); // ["wxh", "hello world"]
Copy the code

Problem 10: Array objects take specified key values

function GetKeys(obj = {}, keys = []) {
    return Object.keys(obj).reduce((t, v) = > (keys.includes(v) && (t[v] = obj[v]), t), {});
}
const cache = { a: 1.b: 2.c: 3.d: 4 };
const keyword = ["a"."d"];
GetKeys(cache, keyword); // { a: 1, d: 4 }
Copy the code

Problem 11: Array to string

const cache = [1.2.3.4];
const str = cache.join(","); // Array to string
const arr = str.split(","); // String to array
Copy the code

Problem 12: Array merge

const cache = [1.2.3.4];
const arr = [...cache, ...cache, ...cache]
Copy the code

Problem 13: Array intersection

const cache = [0.1.2.3.4.5]
const b = [3.4.5.6.7.8]
const joinValue = [...new Set(cache)].filter(item= > b.includes(item)) / / [3, 4, 5]


let cache = [{a:'1'.b:'12'}, {a:'0'.b:'12'}]
let cache1 = [{a:'2'.b:'23'}, {a:'0'.b:'12'}]
let cache2 = cache.map(item= >item.a)
let cache3 = cache1.filter(info= >{
return new Set(cache2).has(info.a)
})
console.log(cache3) // [{a:'0', b:'12'}]
Copy the code
  1. Problem 14: Array difference set
const a = [0.1.2.3.4.5]
const b = [3.4.5.6.7.8]
const diffValues = [...new Set([...a, ...b])].filter(item= >! b.includes(item) || ! a.includes(item))// [0, 1, 2, 6, 7, 8]
Copy the code
  1. Problem 15: Array traversal
// Array traversal
const cache = [0.1.2.3.4.5]
console.log(cache.map(i= > i));

const copy = [];
cache.forEach(function(val, index) {
    copy.push(val);
})

for (var i in cache){
    console.log(i,":",cache[i]);
}

// Object traversal
const cache = [{a:'1'.b:'12'}, {a:'0'.b:'12'}];
Object.keys(cache).forEach(function(key){
     console.log(key,cache[key]);
});
Object.getOwnPropertyNames(cache).forEach(function(key){
    console.log(key,cache[key]);
});

for(var i of cache) {
    console.log(i,":",cache[i]);
}

// contains the Symbol attribute
Reflect.ownKeys(cache).forEach(function(key){
    console.log(key,cache[key]);
});
Copy the code

Problem 16: Check whether there are values in the array that match the condition

/ / array
const cache = [1.2.3.4.5]
const hasNum = cache.some(item= > typeof item === 'number')

/ / object
const reducedFilter = (data, keys, fn) = >
  data.filter(fn).map((el) = >
    keys.reduce((acc, key) = > {
      acc[key] = el[key];
      returnacc; }, {}));const dataFilter = [
  {
    id: 1.name: "john".age: 24}, {id: 2.name: "mike".age: 50,},];console.log(
  "Filter data objects by criteria",
  reducedFilter(dataFilter, ["id"."name"].(item) = > item.age > 24));Copy the code

Check whether all elements in an array meet the criteria

const cache = [1.2.3.4.5]
const isAllNum = cache.every(item= > typeof item === 'number')
Copy the code

Problem 18: Find the first element/subscript that meets the criteria

const cache = [1.2.3.4.5]
const findItem = cache.find(item= > item === 3) // returns the child
const findIndex = cache.findIndex(item= > item === 3) // Returns the subscript of the subitem
Copy the code

Problem 19: shallow/deep copy array

const cache = [1.2.3]
const arrClone = [...cache]
const arrClone = Array.from(cache);
const arrClone = cache.slice(0, cache.length)

const cache = { a: 1 }
constobjClone = { ... cache }function deepClone(object) {
  var clone = {};
  for (var key in object) {
    var value = object[key];
    if (typeof(value) ! = ='object') {
      clone[key] = value;
    } else{ clone[key]=deepClone(value); }}return clone;
} 
const objClone = deepClone(cache)
Copy the code

Problem 20: Array Max and min values

function Max(arr = []) {
    return arr.reduce((t, v) = > t > v ? t : v);
}

function Min(arr = []) {
    return arr.reduce((t, v) = > t < v ? t : v);
}

Copy the code

Problem 21: Array element count

function Count(arr = []) {
    return arr.reduce((t, v) = > (t[v] = (t[v] || 0) + 1, t), {});
}
const cache = [0.1.1.2.2.2];
Count(cache); // {0: 1, 1: 2, 2: 3}
Copy the code

Problem 22: Array element position statistics

function Count(arr = [], val) {
    return arr.reduce((t, v, i) = > (v === val && t.push(i), t), []);
}
const cache = [2.1.5.4.2.1.6.6.7];
Count(cache, 2); / / [0, 4]
Copy the code

Problem 23: Arrays are grouped by elements

function Group(arr = [], key) {
    return key ? arr.reduce((t, v) = >(! t[v[key]] && (t[v[key]] = []), t[v[key]].push(v), t), {}) : {}; }const cache = [
    { city: "GZ".name: "YZW".age: 127 },
    { city: "GZ".name: "TYJ".age: 125 },
    { city: "SZ".name: "AAA".age: 123 },
    { city: "FS".name: "BBB".age: 121 },
    { city: "SZ".name: "CCC".age: 119}];// use city as grouping criteria
Group(cache, "city"); // { GZ: Array(2), SZ: Array(2), FS: Array(1) }
Copy the code

Problem 24: Array URL parameter serialization

function paramsUrl(search = {}) {
    return Object.entries(search).reduce(
        (t, v) = > `${t}${v[0]}=The ${encodeURIComponent(v[1])}& `.Object.keys(search).length ? "?" : ""
    ).replace($/ / &."");
}
paramsUrl({ age: 27.name: "test" }); / / "? age=27&name=test"
Copy the code

Problem 25: Deserialization of array URL parameters

function ParseUrlSearch() {
    return location.search.replace(/ (a ^ \? |(&$)/g."").split("&").reduce((t, v) = > {
        const [key, val] = v.split("=");
        t[key] = decodeURIComponent(val);
        return t;
    }, {});
}
// https://www.baidu.com?age=27&name=test
ParseUrlSearch() // { age: "27", name: "test" }
Copy the code

Problem 26: Array flat

function Flat(arr = []) {
    return arr.reduce((t, v) = > t.concat(Array.isArray(v) ? Flat(v) : v), [])
}

const cache = [0.1[2.3], [4.5[6.7]], [8[9.10[11.12]]]];
Flat(cache); // [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
Copy the code

Problem 27: Array reduce function

const cache = [0.1.2.3];

// Replace map: [0, 2, 4, 6]
const a = cache.map(v= > v * 2);
const b = cache.reduce((t, v) = > [...t, v * 2], []);

// replace filter: [2, 3]
const c = cache.filter(v= > v > 1);
const d = cache.reduce((t, v) = > v > 1 ? [...t, v] : t, []);

// Replace map and filter: [4, 6]
const e = cache.map(v= > v * 2).filter(v= > v > 2);
const f = cache.reduce((t, v) = > v * 2 > 2 ? [...t, v * 2] : t, []);


const cache = [
    { score: 45.subject: "chinese" },
    { score: 90.subject: "math" },
    { score: 60.subject: "english"}];// Instead of some: Pass at least one course
const isAtLeastOneQualified = cache.reduce((t, v) = > t || v.score >= 60.false); // true

// Instead of every: all pass the exam
const isAllQualified = cache.reduce((t, v) = > t && v.score >= 60.true); // false
Copy the code

Problem 28: Array objects get subscripts

const sortedIndexBy = (arr, n, fn) = > {
  const isDescending = fn(arr[0]) > fn(arr[arr.length - 1]);
  const val = fn(n);
  const index = arr.findIndex((el) = >
    isDescending ? val >= fn(el) : val <= fn(el)
  );
  return index === -1 ? arr.length : index;
};
console.log(
  "Get subscript",
  sortedIndexBy([{ x: 14 }, { x: 35}, {x: 35 }, (o) = > o.x) / / 1
); 

Copy the code

Problem 29: Array recursive tree

const nest = (items, id = null, link = "parent_id") = >
  items
    .filter((item) = > item[link] === id)
    .map((item) = > ({ ...item, children: nest(items, item.id, link) }));
const comments = [
  { id: 1.parent_id: null },
  { id: 2.parent_id: 1 },
  { id: 3.parent_id: 1 },
  { id: 4.parent_id: 2 },
  { id: 5.parent_id: 4},];const nestedComments = nest(comments);

console.log("Recursive tree", nestedComments);
Copy the code

Problem 30: Array reduce generates HTML

// The back end returns data
const datas = {
  'name': [
    'wxh'.'wxh'.'wxh',].'age': [
    'wxh'.'wxh'.'wxh']},const _data = Object.entries(datas).reduce((prev, cur) = > {
  const values = cur[1].reduce((prev, cur) = > `${prev}<p>${cur}</p>`.' ')
  return `${prev}
  <li>
      <p>${cur[0]}</p>
      ${values}
    </li>`
}, ' ')

const html = `
  <ul class="nlp-notify-body">
    ${_data}
  </ul>
`
console.log(html);
Copy the code