search
HomeWeb Front-endJS TutorialCommon methods on array in javascript

Recently summarized some common methods in array,

Most of the methods come from the book "JavaScript Framework Design",

If there is a better method, or I hope you will give me some advice on other commonly used methods of string.

Go directly to the code:

/**
 * 判定数组是否包含指定目标
 * @param target
 * @param item
 * @returns {boolean}
 */
function contains(target,item) {
    return target.indexOf(item) > -1;
}

/**
 * 移除数组中指定位置的元素,返回布尔表示成功与否
 * @param target
 * @param index
 * @returns {boolean}
 */
function removeAt(target,index) {
    return !!target.splice(index,1).length;
}

/**
 * 移除数组中第一个匹配传参的那个元素,返回布尔表示成功与否
 * @param target
 * @param item
 * @returns {boolean}
 */
function remove(target,item) {
    const index = target.indexOf(item);
    if (~index) {
        return removeAt(target,index);
    }
    return false;
}

/**
 * 对数组进行洗牌
 * @param array
 * @returns {array}
 */
function shuffle(array) {
    let m = array.length, t, i;
    // While there remain elements to shuffle…
    while (m) {
        // Pick a remaining element…
        i = Math.floor(Math.random() * m--);

        // And swap it with the current element.
        t = array[m];
        array[m] = array[i];
        array[i] = t;
    }
    return array;
}

/**
 * 从数组中随机抽选一个元素出来
 * @param target
 * @returns {*}
 */
function random(target) {
    return target[Math.floor(Math.random() * target.length)];
}

/**
 * 对数组进行平坦化处理,返回一个一维的新数组
 * @param target
 * @returns {Array}
 */
function flatten (target) {
    let result = [];
    target.forEach(function(item) {
        if(Array.isArray(item)) {
            result = result.concat(flatten(item));
        } else {
            result.push(item);
        }
    });
    return result;
}

/**
 * 去重操作,有序状态
 * @param target
 * @returns {Array}
 */
function unique(target) {
    let result = [];
    loop: for (let i = 0,n = target.length;i < n; i++) {
        for (let x = i + 1;x < n;x++) {
            if (target[x] === target[i]) {
                continue loop;
            }
        }
        result.push(target[i]);
    }
    return result;
}

/**
 * 去重操作,无序状态,效率最高
 * @param target
 * @returns {Array}
 */
function unique1(target) {
    let obj = {};
    for (let i = 0,n = target.length; i < n;i++) {
        obj[target[i]] = true;
    }
    return Object.keys(obj);
}

/**
 * 过滤属性中的null和undefined,但不影响原数组
 * @param target
 * @returns {Array.<T>|*}
 */
function compat(target) {
    return target.filter(function(el) {
        return el != null;
    })
}

/**
 * 根据指定条件(如回调或对象的某个属性)进行分组,构成对象返回。
 * @param target
 * @param val
 * @returns {{}}
 */
function groupBy(target,val) {
    var result = {};
    var iterator = isFunction(val) ? val : function(obj) {
        return obj[val];
    };
    target.forEach(function(value,index) {
        var key = iterator(value,index);
        (result[key] || (result[key] = [])).push(value);
    });
    return result;
}
function isFunction(obj){
    return Object.prototype.toString.call(obj) === &#39;[object Function]&#39;;
}

// 例子
function iterator(value) {
   if (value > 10) {
       return &#39;a&#39;;
   } else if (value > 5) {
       return &#39;b&#39;;
   }
   return &#39;c&#39;;
}
var target = [6,2,3,4,5,65,7,6,8,7,65,4,34,7,8];
console.log(groupBy(target,iterator));



/**
 * 获取对象数组的每个元素的指定属性,组成数组返回
 * @param target
 * @param name
 * @returns {Array}
 */
function pluck(target,name) {
    let result = [],prop;
    target.forEach(function(item) {
        prop = item[name];
        if (prop != null) {
            result.push(prop);
        }
    });
    return result;
}

/**
 * 根据指定条件进行排序,通常用于对象数组
 * @param target
 * @param fn
 * @param scope
 * @returns {Array}
 */
function sortBy(target,fn,scope) {
    let array = target.map(function(item,index) {
        return {
            el: item,
            re: fn.call(scope,item,index)
        };
    }).sort(function(left,right) {
        let a = left.re, b = right.re;
        return a < b ? -1 : a > b ? 1 : 0;
    });
    return pluck(array,&#39;el&#39;);
}

/**
 * 对两个数组取并集
 * @param target
 * @param array
 * @returns {Array}
 */
function union(target,array) {
    return unique(target.concat(array));
}

/**
 * 对两个数组取交集
 * @param target
 * @param array
 * @returns {Array.<T>|*}
 */
function intersect(target,array) {
    return target.filter(function(n) {
        return ~array.indexOf(n);
    })
}

/**
 * 返回数组中的最小值,用于数字数组
 * @param target
 * @returns {*}
 */
function min(target) {
    return Math.min.apply(0,target);
}

/**
 * 返回数组中的最大值,用于数字数组
 * @param target
 * @returns {*}
 */
function max(target) {
    return Math.max.apply(0,target);
}

Finally simulate the implementation principle of pop, oush, shift and unshift in the array

const _slice = Array.prototype.slice;
Array.prototype.pop = function() {
    return this.splice(this.length - 1,1)[0];
};
Array.prototype.push = function() {
    this.splice.apply(this,[this.length,0].concat(_slice.call(arguments)));
    return this.length;
};
Array.prototype.shift = function() {
    return this.splice(0,1)[0];
};
Array.prototype.unshift = function() {
    this.splice.apply(this,
        [0,0].concat(_slice.call(arguments)));
    return this.length;
};

The above is the detailed content of Common methods on array in javascript. For more information, please follow other related articles on the PHP Chinese website!

Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Python vs. JavaScript: A Comparative Analysis for DevelopersPython vs. JavaScript: A Comparative Analysis for DevelopersMay 09, 2025 am 12:22 AM

The main difference between Python and JavaScript is the type system and application scenarios. 1. Python uses dynamic types, suitable for scientific computing and data analysis. 2. JavaScript adopts weak types and is widely used in front-end and full-stack development. The two have their own advantages in asynchronous programming and performance optimization, and should be decided according to project requirements when choosing.

Python vs. JavaScript: Choosing the Right Tool for the JobPython vs. JavaScript: Choosing the Right Tool for the JobMay 08, 2025 am 12:10 AM

Whether to choose Python or JavaScript depends on the project type: 1) Choose Python for data science and automation tasks; 2) Choose JavaScript for front-end and full-stack development. Python is favored for its powerful library in data processing and automation, while JavaScript is indispensable for its advantages in web interaction and full-stack development.

Python and JavaScript: Understanding the Strengths of EachPython and JavaScript: Understanding the Strengths of EachMay 06, 2025 am 12:15 AM

Python and JavaScript each have their own advantages, and the choice depends on project needs and personal preferences. 1. Python is easy to learn, with concise syntax, suitable for data science and back-end development, but has a slow execution speed. 2. JavaScript is everywhere in front-end development and has strong asynchronous programming capabilities. Node.js makes it suitable for full-stack development, but the syntax may be complex and error-prone.

JavaScript's Core: Is It Built on C or C  ?JavaScript's Core: Is It Built on C or C ?May 05, 2025 am 12:07 AM

JavaScriptisnotbuiltonCorC ;it'saninterpretedlanguagethatrunsonenginesoftenwritteninC .1)JavaScriptwasdesignedasalightweight,interpretedlanguageforwebbrowsers.2)EnginesevolvedfromsimpleinterpreterstoJITcompilers,typicallyinC ,improvingperformance.

JavaScript Applications: From Front-End to Back-EndJavaScript Applications: From Front-End to Back-EndMay 04, 2025 am 12:12 AM

JavaScript can be used for front-end and back-end development. The front-end enhances the user experience through DOM operations, and the back-end handles server tasks through Node.js. 1. Front-end example: Change the content of the web page text. 2. Backend example: Create a Node.js server.

Python vs. JavaScript: Which Language Should You Learn?Python vs. JavaScript: Which Language Should You Learn?May 03, 2025 am 12:10 AM

Choosing Python or JavaScript should be based on career development, learning curve and ecosystem: 1) Career development: Python is suitable for data science and back-end development, while JavaScript is suitable for front-end and full-stack development. 2) Learning curve: Python syntax is concise and suitable for beginners; JavaScript syntax is flexible. 3) Ecosystem: Python has rich scientific computing libraries, and JavaScript has a powerful front-end framework.

JavaScript Frameworks: Powering Modern Web DevelopmentJavaScript Frameworks: Powering Modern Web DevelopmentMay 02, 2025 am 12:04 AM

The power of the JavaScript framework lies in simplifying development, improving user experience and application performance. When choosing a framework, consider: 1. Project size and complexity, 2. Team experience, 3. Ecosystem and community support.

The Relationship Between JavaScript, C  , and BrowsersThe Relationship Between JavaScript, C , and BrowsersMay 01, 2025 am 12:06 AM

Introduction I know you may find it strange, what exactly does JavaScript, C and browser have to do? They seem to be unrelated, but in fact, they play a very important role in modern web development. Today we will discuss the close connection between these three. Through this article, you will learn how JavaScript runs in the browser, the role of C in the browser engine, and how they work together to drive rendering and interaction of web pages. We all know the relationship between JavaScript and browser. JavaScript is the core language of front-end development. It runs directly in the browser, making web pages vivid and interesting. Have you ever wondered why JavaScr

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 English version

SublimeText3 English version

Recommended: Win version, supports code prompts!

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)