数组的去重、获取下标、删除、添加等各种操作

1.数组去除空值

function filter_array(array) {  
  return array.filter(item=>item); 
} 
//JS
var t = [false, null, 0, NaN, undefined, "",'aaaa']; 
t.filter(function (item) { return item });
t.filter(function (item) { return item.IsCurrent == true;}

2.通过某元素获取在数组中对应的下标(也是判断是否存在于这个数组中)

//ES6
var t = [{id:1},{id:2},{id:3}]; 
var tt = {id:3}; 
t.map(item => item.id ).indexOf(tt.id)
//JS
var t = [{id:1},{id:2},{id:3}]; 
var tt = {id:3}; 
t.map(function (item) { return item.id}).indexOf(tt.id)

3.改变数组对象中元素的值

//JS
var t = [{id:1},{id:2},{id:3}]; 
t.map(function (item) { return item.id = 55})

4.数组去重

let arr = [1,2,3,4,4,1]
let newArr = arr.reduce((pre,cur)=>{
    if(!pre.includes(cur)){
      return pre.concat(cur)
    }else{
      return pre
    }
},[])
console.log(newArr);// [1, 2, 3, 4]

5.计算数组中每个元素出现的次数

let names = ['Alice', 'Bob', 'Tiff', 'Bruce', 'Alice'];

let nameNum = names.reduce((pre,cur)=>{
  if(cur in pre){
    pre[cur]++
  }else{
    pre[cur] = 1 
  }
  return pre
},{})
console.log(nameNum); //{Alice: 2, Bob: 1, Tiff: 1, Bruce: 1}

6.对象里的属性求和

var result = [
    {
        subject: 'math',
        score: 10
    },
    {
        subject: 'chinese',
        score: 20
    },
    {
        subject: 'english',
        score: 30
    }
];

var sum = result.reduce(function(prev, cur) {
    return cur.score + prev;
}, 0);
console.log(sum) //60

你可能感兴趣的:(数组的去重、获取下标、删除、添加等各种操作)