項目の配列を map()
関数でフィルタリングしたいのですが、どうすればいいですか?以下はコードスニペットです。
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
問題は、フィルタリングされた項目がまだ配列のスペースを使用していることで、私はそれらを完全に消去したいと思います。
何かアイデアはありますか?
EDIT: ありがとう、filter()
のことを忘れていました。私が欲しかったのは実際には filter()
の後に map()
です。
EDIT2: map()
と filter()
がすべてのブラウザで実装されているわけではないことをご指摘いただき、ありがとうございました。
ただし、Array.filter
はすべてのブラウザでサポートされているわけではないので、プロトタイプを作成する必要があることに注意してください。
//This prototype is provided by the Mozilla foundation and
//is distributed under the MIT license.
//http://www.ibiblio.org/pub/Linux/LICENSES/mit.license
if (!Array.prototype.filter)
{
Array.prototype.filter = function(fun /*, thisp*/)
{
var len = this.length;
if (typeof fun != "function")
throw new TypeError();
var res = new Array();
var thisp = arguments[1];
for (var i = 0; i < len; i++)
{
if (i in this)
{
var val = this[i]; // in case fun mutates this
if (fun.call(thisp, val, i, this))
res.push(val);
}
}
return res;
};
}
そうすることで、必要なメソッドをプロトタイプ化することができます。