当前位置:网站首页>Array common methods

Array common methods

2022-06-22 02:07:00 Xiaobai learns programming together

filter Filter

Use filter Filter out qualified objects

let areaList = result.filter(obj => {
    
							return obj.elabel == item
						})

sort Sort

  • Affect original array
  • No return value
  • Pass in two values before and after
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            //  Yes  fruits  The elements in are sorted 


var arr = [1,3,2,5,4]
arr.sort((a,b)=>{
    
	return a-b
})

JS Get an attribute collection of the object array

var data = [
    {
    
        a: 1,
        b: 2,
        c: 3
    },
    {
    
        a: 4,
        b: 5,
        c: 6
    },
    {
    
        a: 7,
        b: 8,
        c: 9
    }
];

//  Used  ES6  grammar 
data.map(item => item.a)

//  Compatible writing 
data.map(function (item) {
    
    return item.a;
});

java Get a property collection in the object collection

js Deweight the array
ES6 In the use of Set duplicate removal

function newArr(arr){
    
    return Array.from(new Set(arr))
}
 
var arr = [1,1,2,9,6,9,6,3,1,4,5];
 
console.log(newArr(arr))

Create a new array , utilize indexOf duplicate removal


function newArr(array){
     
    // A new array  
    var arrs = []; 
    // Traverse current array  
    for(var i = 0; i < array.length; i++){
     
        // If there is no current value of the current array in the temporary array , The current value push Into the new array  
        if (arrs.indexOf(array[i]) == -1){
     
            arrs.push(array[i])
        }; 
    } 
    return arrs; 
}
 
var arr = [1,1,2,5,5,6,8,9,8];
 
console.log(newArr(arr))

for A nested loop , utilize splice duplicate removal

function newArr(arr){
    
    for(var i=0;i<arr.length;i++){
    
        for(var j=i+1;j<arr.length;j++){
    
            if(arr[i]==arr[j]){
     
            // If the first is equal to the second ,splice Method to delete the second 
            arr.splice(j,1);
            j--;
            }
        }
    }
    return arr;
}
 
var arr = [1,1,2,5,6,3,5,5,6,8,9,8];
 
console.log(newArr(arr))

sort() Method sorts the array alphabetically :

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.sort();            //  Yes  fruits  The elements in are sorted 

原网站

版权声明
本文为[Xiaobai learns programming together]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220146202707.html