Home  >  Article  >  Web Front-end  >  Introduction to commonly used operations in javascript arrays (code examples)

Introduction to commonly used operations in javascript arrays (code examples)

不言
不言forward
2019-03-19 11:02:192418browse


This article brings you an introduction to common operations (code examples) in JavaScript arrays. It has certain reference value. Friends in need can refer to it. I hope It will help you.

1. Do not change the original array, return a new array (string)

1. concat() connects two or more arrays, the original arrays on both sides will not change, and the returned is a copy of the concatenated array.

2. join() Put all the elements in the array into a string and return the string

var a = [1,2,3];
a.join([4,5,6]);    //  "14,5,624,5,63"
a.join('sau');      //  "1sau2sau3"

3. slice() Select from the beginning to the end (excluding the end) Shallow copy a part of the array to a new array

var a  = [1,2,3,4,5];
a.slice(0,0);     //[]
a.slice(0,1);     //[1]
a.slice(2,4);    //[3,4]
a.slice(0,5);    //[1,2,3,4,5]
a.slice(10,1);   //[]
a.slice(4);   //[5]

4. map() creates a new array and returns it. Each element of the new array is obtained by calling each element in the original array to execute the provided function. Next, the original array remains unchanged

5. every() executes the specified callback function once for each element in the array until the callback function returns false. At this time, every() returns false and does not continue execution. , if the callback function returns true for every element, then every() returns true.

6. some() executes the specified callback function once for each element in the array until the callback function returns true. At this time, some() returns true and is no longer executed. If the callback function returns false for every element, then some() will return false.

7. filter() Creates a new array containing all elements of the test implemented by the provided function.

2. Change the original array

1. forEach() executes the provided function for each element. The original array will be modified, the execution result will not be returned, and undefined will be returned.

2. pop() deletes the last element of the array and returns the value of the deleted element. If the array is empty, the array is not changed and undefined is returned.

3. push() adds one or more elements to the end of the array and returns the changed length of the array.

4. reverse() reverses the position of the elements in the array and returns a reference to the array.

5. shift() removes the first element from the array, changes the original array, and returns the value of the element.

6. unshift() Adds one or more elements to the beginning of the array and returns the length of the new array.

7. sort() Sorts the elements of the array and returns the array. Sorting is not necessarily stable. The default sort order is based on string unicode code points.

8. splice() adds/removes elements to the array, and then returns the deleted new array().

var a  = [1,2,3,4,5];
a.splice(0,1);     //删除从0位置开始的1个   返回[1]   a为[2,3,4,5] 
a.splice(1,0,99)   //在1的位置插入99   [2,99,3,4,5]
a.splice(1,1,88)   //99替换为88  [2,88,3,4,5]

3. Traversal method

1. Get the attribute name: The difference between for...in and object.key()

Answer: 1. for in traverses the list of property names that can be enumerated by the object, including the [[prototype]] prototype chain;

2. Object.keys() only checks whether the property name is in the object and returns an array containing All enumerable property names;

3. Object.getOwnPropertyNames() only checks whether the property name is in the object and returns an array containing all property names, whether enumerable or not.

2. Get attribute values: for... of and object.values()

for of statement: traverse the enumerable attribute value list of the iterable object, including [[propertype] ] Prototype chain;

object.values(): Returns the values ​​of all enumerable properties of a given object itself, excluding the prototype chain.

4. Convert ES6 syntax Map key-value pairs into arrays

new Map creates a map

// new Map创建一个map
let map = new Map([[1,"one"], [2,"two"], [3,"three"]]);
map.set(4, "four");
// 获取所有键值对
console.log("获取key")
console.log([...map.keys()]) // 输出[1, 2, 3, 4]

console.log("获取value")
console.log([...map.values()]) // 输出[one, two, three, four]

console.log("获取map数组")
console.log([...map]) // 输出[[1, "one"], [2, "two"], [3, "three"], [4, "four"]]

5. Two ascending ones Merge the arrays into an ascending array

1. Time complexity O(M N), space complexity O(M N)

function merge(left, right){
    let result  = [],
        il      = 0,
        ir      = 0;

    while (il < left.length && ir < right.length) {
        result.push(left[il] < right[ir] ? left[il++] : right[ir++]);
console.log(result);
    }

    return result.concat(left.slice(il)).concat(right.slice(ir));
}

2. Time complexity O(M N), space Complexity O(1)

   // m, n 是数组长度
function merge(left, m, right,  n) {
    var i = m - 1, j = n - 1, writeIdx = m + n - 1;
    while (i >= 0 && j >= 0)
    left[writeIdx--] = left[i] > right[j]? left[i--] : right[j--];
    while (j >= 0)
    left[writeIdx--] = right[j--];
    return left;
}

6. Array duplication problem

(1) Array deduplication

1. Reduce method

const distinct = arr => arr.sort().reduce( (init, current) => {
    
    if (init.length === 0 || init[init.length - 1] !== current) {
        init.push( current );
    }
    return init;
}, []);

let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
distinct(arr); // [1, 2, 3, 4, 5]

2. Filter method

const distinct = arr => arr.filter( (element, index, self) => {

return self.indexOf( element ) === index;
});
let arr = [1,2,1,2,3,5,4,5,3,4,4,4,4];
distinct(arr); // [1, 2, 3, 5, 4]

(2) Sorted array deduplication

/**
 * @param {number[]} nums
 * @return {number}
 */
var removeDuplicates = function(nums) {
    
    if(!nums || nums.length == 0) return 0;
    
    let len = 0;
    for(let i = 1; i < nums.length; i++) {
        if (nums[len] != nums[i]) {
            nums[++ len] = nums[i];
        }
    }
    return len + 1;
};

(3) Determine whether there are duplicates in the array

/**
 * @param {number[]} nums
 * @return {boolean}
 */
var containsDuplicate = function(nums) {
    
    let hashMap = new Map();
    for(let i = 0; i < nums.length; i++) {
        
        if( hashMap.has(nums[i]) ) {
           return true;
        }
        
        hashMap.set(nums[i], 1);
    }
    
    return false;
};

7. Intersection of two arrays

Given two arrays, write a method to calculate their intersection.

For example:

Given nums1 = [1, 2, 2, 1], nums2 = [2, 2], return [2, 2].

Note: 1. The number of occurrences of each element in the output result should be consistent with the number of occurrences of the element in the two arrays. 2.

We can ignore the order of the output results.
Follow up: 1. What if the given array is already sorted? How would you optimize your algorithm? 2. If the size of nums1 is much smaller than nums2, which method is better? 3. If the elements of nums2 are stored on disk, memory is limited Yes, you can't load all the elements into memory at once, what should you do?

Solution:

/**
 * @param {number[]} nums1
 * @param {number[]} nums2
 * @return {number[]}
 */
var intersect = function(nums1, nums2) {
    
    var map1 = new Map();
    var number = [];
    
    for(var i = 0; i < nums1.length; i++) {
        var map1Value = map1.get(nums1[i]);
        map1.set( nums1[i], ( map1Value ? map1Value : 0 ) + 1 );
    }
    
    for(var i = 0; i < nums2.length; i++) {
        if( map1.has(nums2[i]) && map1.get(nums2[i]) != 0 ) {
            number.push(nums2[i]);
            map1.set( nums2[i], map1.get(nums2[i]) - 1 );
        }
    }
    
    return number;
};

8. Find the number that only appears once in an array

给定一个非空整数数组,除了某个元素只出现一次以外,其余每个元素均出现两次。找出那个只出现了一次的元素。

/**
 * @param {number[]} nums
 * @return {number}
 */
var singleNumber = function(nums) {
    
    let number = 0;
    for(let i = 0; i < nums.length; i++) {
        number ^= nums[i];
    }
    return number;
};

本篇文章到这里就已经全部结束了,更多其他精彩内容可以关注PHP中文网的JavaScript教程视频栏目!

The above is the detailed content of Introduction to commonly used operations in javascript arrays (code examples). For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:segmentfault.com. If there is any infringement, please contact admin@php.cn delete