小言_互联网的博客

js 数组常用方法

266人阅读  评论(0)

 一、创建数据

var arr1 = [1, 2, 3, 4, 5],
    arr2 = [2, 4, 6, 8, 10];

 

二、数组增删改查

  新增数据

// 头部新增:方法二效率更高
arr1.unshift(0);
var newArr = [0].concat(arr1); 

// 中间新增:splice(索引位置, 删除个元素, 新增元素);
arr1.splice(2,0,9);

// 尾部新增:方法二效率更高
arr1[arr1.length] = 1;
arr1.push(1);

 

  删除数据

// 头部删除:
arr1.shift();

// 中间删除:splice(索引位置, 删除个元素);
arr1.splice(2,1);

// 尾部删除:
arr1.pop();

 

   修改数据

// 修改数据:数组[索引] = 值
arr1[1] = 123;

 

   查询数据

// 从前往后开始查找元素在数组中的索引
arr1.indexOf(1);

// 从后往前开始查找元素在数组中的索引
arr1.lastIndexOf(1);

 

三、数组遍历效率比较 

  遍历效率最快

for(var i = 0, len = arr1.length; i < len; i++){
    console.log(arr1[i])
}

 

  带索引遍历

arr1.forEach((value, index, array) => console.log('arr1[' + index + '] = ' + value));

 

  数组遍历效率对比

   

 

四、数组常用API方法 

  sort 排序

// 正序:
arr1.sort();

// 逆序
arr1.sort().reverse();
// 定制排序:只对数字类型有效
arr1.sort((a, b) => a-b);
arr1.sort((a, b) => b-a);
// 定制排序:按照某个属性排序
var items = [
    { name: 'Edward', value: 21 },
    { name: 'Sharpe', value: 37 },
    { name: 'And', value: 45 },
    { name: 'The', value: -12 },
    { name: 'Magnetic', value: 32 },
    { name: 'Zeros', value: 37 }
];
items.sort(function (a, b) {
    return (a.value - b.value)
});

 

  slice 克隆数组

var arr3 = arr1.slice()

 

  concat 数组合并

// 合并两个或多个数组:arr3 = arr1 + arr2
var arr3 = arr1.concat(arr2);

 

   from  转换( IE 不支持):

// 字符串转数组
Array.from('foo'); // ["f", "o", "o"]

// set转数组
Array.from(new Set(['foo', window])); // ["foo", window]

// map转数组
Array.from(new Map([[1, 2], [2, 4], [4, 8]])); // [[1, 2], [2, 4], [4, 8]]

// 方法形参转数组
function f() {
    return Array.from(arguments);
}
f(1, 2, 3); // [1, 2, 3]

// 在Array.from中使用箭头函数
Array.from([1, 2, 3], x => x + x);
// x => x + x代表这是一个函数,只是省略了其他的定义,这是一种Lambda表达式的写法
// 箭头的意思表示从当前数组中取出一个值,然后自加,并将返回的结果添加到新数组中
// [2, 4, 6]

 

   isArray 判断是否是数组类型

Array.isArray([1, 2, 3]); 

 

    every  判断所有元素是否都通过了指定函数测试

function isBigEnough(element, index, array) {
    return (element >= 10);
}

var passed = [12, 5, 8, 130, 44].every(isBigEnough); // passed is false
passed = [122, 54, 128, 130, 44].every(isBigEnough); // passed is true

 

    some 判断所有元素至少有一个通过了指定函数测试

function isBiggerThan10(element, index, array) {
    return element > 10;
}

[2, 5, 8, 1, 4].some(isBiggerThan10);  // false
[12, 5, 8, 1, 4].some(isBiggerThan10); // true

 

    join 数组拼接

var a = ['Wind', 'Rain', 'Fire'];
var myVar1 = a.join();     // myVar1的值变为"Wind,Rain,Fire"
var myVar2 = a.join(', '); // myVar2的值变为"Wind, Rain, Fire"
var myVar3 = a.join(' + ');// myVar3的值变为"Wind + Rain + Fire"
var myVar4 = a.join('');   // myVar4的值变为"WindRainFire"

 

     filter 筛选排除

function isBigEnough(element) {
    return element >= 3;
}

var filtered = arr1.filter(isBigEnough); // filtered is [3, 4, 5]

 

     map 数组中的每个元素都调用一个提供的函数后返回的结果

const map1 = arr1.map(x => x * 2);
// expected output: Array [2, 4, 5, 8, 10]

var users = [
    {"name": "张含韵", "email": "zhang@email.com"},
    {"name": "江一燕", "email": "jiang@email.com"},
    {"name": "李小璐", "email": "li@email.com"}
];
var emails = users.map(value => value.email);
console.log(emails.join(", ")); // zhang@email.com, jiang@email.com, li@email.com

 

     reduce 规约

const array1 = [1, 2, 3, 4];
const reducer = (accumulator, currentValue) => accumulator + currentValue;

console.log(array1.reduce(reducer));
// 1 + 2 + 3 + 4   expected output: 10

 

五、数组常用方法 

  并集

// 不去重的并集
var arr3 = [1, 2, 3].concat([4, 3, 2]); // [1, 2, 3, 4, 3, 2]

// 去重后的并集
const union = (a, b) => Array.from(new Set([...a, ...b]));
union([1, 2, 3], [4, 3, 2]); // [1,2,3,4]

// 去重后的并集,并向上取整
const unionWith = (a, b, comp) =>
    Array.from(new Set([...a, ...b.filter(x => a.findIndex(y => comp(x, y)) === -1)]));
unionWith([1, 1.2, 1.5, 3, 0], [1.9, 3, 0, 3.9], (a, b) => Math.round(a) === Math.round(b));
// [1, 1.2, 1.5, 3, 0, 3.9]

 

  交集

const intersection = (a, b) => {
    const s = new Set(b);
    return a.filter(x => s.has(x));
};
intersection([1, 2, 3], [4, 3, 2]); // [2, 3]

 

  差集 

const difference = (a, b) => {
    const s = new Set(b);
    return a.filter(x => !s.has(x));
};
difference([1, 2, 3], [1, 2, 4]); // [3]


// 不筛选重复
const 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))];
};
symmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
symmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 2, 3]

const uniqueSymmetricDifference = (a, b) => [
    ...new Set([...a.filter(v => !b.includes(v)), ...b.filter(v => !a.includes(v))])
];
uniqueSymmetricDifference([1, 2, 3], [1, 2, 4]); // [3, 4]
uniqueSymmetricDifference([1, 2, 2], [1, 3, 1]); // [2, 3]

const symmetricDifferenceBy = (a, b, fn) => {
    const sA = new Set(a.map(v => fn(v))),
    sB = new Set(b.map(v => fn(v)));
    return [...a.filter(x => !sB.has(fn(x))), ...b.filter(x => !sA.has(fn(x)))];
};
symmetricDifferenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); // [ 1.2, 3.4 ]

 

  数组扁平化

// 递归:数组扁平化
const deepFlatten = arr => [].concat(...arr.map(v => (Array.isArray(v) ? deepFlatten(v) : v)));
deepFlatten([1, [2], [[3], 4], 5]); // [1,2,3,4,5]

// 递归:数组对象扁平化,指定深度
const flatten = (arr, depth = 1) =>
    arr.reduce((a, v) => a.concat(depth > 1 && Array.isArray(v) ? flatten(v, depth - 1) : v), []);
flatten([1, [2], 3, 4]); // [1, 2, 3, 4]
flatten([1, [2, [3, [4, 5], 6], 7], 8], 2); // [1, 2, 3, [4, 5], 6, 7, 8]


// 递归:多级嵌套的数组对象扁平化
function loopTree(data, children, resultData) {
    $.each(data, function (index, rootObject) {
        var row = {};
        $.each(rootObject, function (name, value) {
            if (name != children) {
                row[name] = value;
            }
        })
        resultData.push(row);
        if(rootObject.children == undefined){
            return true;
        } else {
            loopTree(rootObject.children, children, resultData);
        }
    })
}

 

  数组去重

// 数组去重,合并
function combine(){
    let arr = [].concat.apply([], arguments); //没有去重复的新数组
    return Array.from(new Set(arr));
}

var m = [1, 2, 2], n = [2,3,3];
console.log(combine(m,n)); // [1, 2, 3]

 

  删除数组中重复值

const filterNonUnique = arr => arr.filter(i => arr.indexOf(i) === arr.lastIndexOf(i));
filterNonUnique([1, 2, 2, 3, 4, 4, 5]); // [1, 3, 5]

 

   删除数组中假值

const compact = arr => arr.filter(Boolean);

compact([0, 1, false, 2, '', 3, 'a', 'e' * 23, NaN, 's', 34]); 
// [ 1, 2, 3, 'a', 's', 34 ]

 

   返回数组中唯一值

const filterNonUniqueBy = (arr, fn) =>
    arr.filter((v, i) => arr.every((x, j) => (i === j) === fn(v, x, i, j)));

filterNonUniqueBy(
    [
        { id: 0, value: 'a' },
        { id: 1, value: 'b' },
        { id: 2, value: 'c' },
        { id: 1, value: 'd' },
        { id: 0, value: 'e' }
    ],
    (a, b) => a.id == b.id
); // [ { id: 2, value: 'c' } ]

 

   查询元素在数组中出现的次数

const countOccurrences = (arr, val) => arr.reduce((a, v) => (v === val ? a + 1 : a), 0);
countOccurrences([1, 1, 2, 1, 2, 3], 1); // 3

 

   每组元素计数

const countBy = (arr, fn) =>
    arr.map(typeof fn === 'function' ? fn : val => val[fn]).reduce((acc, val) => {
        acc[val] = (acc[val] || 0) + 1;
        return acc;
    }, {});

countBy([6.1, 4.2, 6.3], Math.floor); // {4: 1, 6: 2}
countBy(['one', 'two', 'three'], 'length'); // {3: 2, 5: 1}

 

   根据条件筛选对象数组,同时筛选出未指定的键

const reducedFilter = (data, keys, fn) =>
    data.filter(fn).map(el =>
        keys.reduce((acc, key) => {
            acc[key] = el[key];
            return acc;
        }, {})
    );

const data = [
    {
        id: 1,
        name: 'john',
        age: 24
    },
    {
        id: 2,
        name: 'mike',
        age: 50
    }
];

reducedFilter(data, ['id', 'name'], item => item.age > 24); // [{ id: 2, name: 'mike'}]

 


转载:https://blog.csdn.net/han12398766/article/details/101034180
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场