5つの配列Aray方法:indexOf、filter、forEach、map、reduce使用例

10149 ワード

 ES5 ,   9 Array   :

 Array.prototype.indexOf
 Array.prototype.lastIndexOf
 Array.prototype.every
 Array.prototype.some
 Array.prototype.forEach
 Array.prototype.map
 Array.prototype.filter
 Array.prototype.reduce
 Array.prototype.reduceRight
1.indexOf
  indexOf()方法は、配列の中で最初に見つかった要素位置を返します.存在しない場合は-1を返します.
入力:
var arr = ['apple','orange','pear'];

console.log("found:", arr.indexOf("orange") );
出力:
found: 1
2.filter
このfilter()法は新しい整合フィルタ条件の配列を作成する.
入力:
var arr = [
  {"name":"apple", "count": 2},
  {"name":"orange", "count": 5},
  {"name":"pear", "count": 3},
  {"name":"orange", "count": 16},
];

var newArr = arr.filter(function(item){
    return item.name=='orange';
})

console.log("Filter results:",newArr.toString());

出力:
Filter results: [{"name":"orange","count":5},{"name":"orange","count":16}]
3.forEach
_; forEachは各要素に対応する方法を実行します.
入力:
var arr = [1,2,3,4,5,6,7,8];

arr.forEach(function(item,index){
console.log("item:"+item+",index:"+index);
});

出力:
item:1,index:0
item:2,index:1
item:3,index:2
item:4,index:3
item:5,index:4
item:6,index:5
item:7,index:6
item:8,index:7
4.map()
行列の要素ごとに一定の操作(マッピング)を行うと、新しい配列が返されます.
入力:
var oldArr = 
[{first_name:"Colin",last_name:"Toh"},
{first_name:"Addy",last_name:"Osmani"},
{first_name:"Yehuda",last_name:"Katz"}];

function getNewArr(){
    return oldArr.map(function(item,index){
        item.full_name = [item.first_name,item.last_name].join(" ");
        return item;
    }); 
}
console.log(getNewArr());
出力:
[{"first_name":"Colin","last_name":"Toh","full_name":"Colin Toh"},{"first_name":"Addy","last_name":"Osmani","full_name":"Addy Osmani"},{"first_name":"Yehuda","last_name":"Katz","full_name":"Yehuda Katz"}]
5.reduce()
これらのアキュムレータは、配列の各値(左から右へ)を一つの値に下げるアキュムレータ機能を実現することができる.
入力:
var arr = ["apple","orange","apple","orange","pear","orange"];

function getWordCnt(){
  return arr.reduce(function(prev,next){
console.log("prev:"+JSON.stringify(prev)+",next:"+next)
    prev[next] = (prev[next] + 1) || 1;
    return prev;
  },{});
}

console.log(JSON.stringify(getWordCnt()));
出力:
prev:{},next:apple
prev:{"apple":1},next:orange
prev:{"apple":1,"orange":1},next:apple
prev:{"apple":2,"orange":1},next:orange
prev:{"apple":2,"orange":2},next:pear
prev:{"apple":2,"orange":2,"pear":1},next:orange
VM401:11 {"apple":2,"orange":3,"pear":1}