map()` 함수를 사용하여 항목 배열을 필터링하고 싶습니다. 다음은 코드 스니펫입니다:
var filteredItems = items.map(function(item)
{
if( ...some condition... )
{
return item;
}
});
문제는 필터링된 항목이 여전히 배열의 공간을 사용하므로 완전히 지우고 싶다는 것입니다.
어떤 방법이 있을까요?
편집 : 고마워, 나는 필터 ()
에 대해 잊어 버렸습니다, 내가 원하는 것은 실제로 필터 ()
다음 지도 ()
입니다.
편집 2 : 내 특정 코드가 브라우저에서 실행되도록 의도 된 것은 아니지만 map ()
및 filter ()
가 모든 브라우저에서 구현되지 않는다는 점을 지적 해 주셔서 감사합니다.
내가 답을 작성했습니까 귈이예요 이제 다시, 내 의견을 바뀌었다. 난 내 추천합니까 체크아웃하기 [블로그 포스트] (http://code.blog.kylebaker.io/2018/03/15/stack-overflow/) 이 이 훨씬 더 나은 주제와 어떤 식으로 설명합니다. 또한 에스페르프 끝날 수 있는 대안 비교.
' [1.2,3] 윈필터 (num = >. num >. 2) 오마프 (num = >. num * 2) '
사용법은 라이트러더스 () '는' 는 어떤 inet6.0, 어떻게 처리할 수 있는 한 이터레이션에 필터 및 매핑해야 사용할 수 있습니다. 이 경우, 이는 높은 것을, 내가 너무 압축됨 추천합니까 블로그 포스트를 그들위에 링크됨 훨씬 더 친화적임 소개 분명한 사례 및 추이.
이는 절감하십시오 인수를 (주로 익명) 기능을 부여할 수 있습니다.
참고 있는 반면 라이트필터 () 는 오직 하나의 인수 (함수), 라이트러더스 () 는 또한 중요한 (선택적이며) 두 번째 인수: # 39, & # 39 의 초기값을 memo&. 그 역할을 할 수 있는 첫 번째 인수는 에 전달되고, 그 이후에 있었던 익명 함수 호출 간의 따라 변형된다. (# 39, & # 39 memo& 관심용 공급되지 않는 경우. 첫 번째 익명 함수 호출은 이트라티 # 39, & # 39 (be the first), 그리고 기본적으로 iteratee&. 실제 사용될 인수는 값이 두 번째 배열)
이렇게 하면 한 수를 줄이고 이터레이션인지 필터 및 매핑됩니까 일어날 수 있는 우리 필요한 이터레이션에 반단면. )
대한 보다 자세한 설명,) 은 다음과 같은 뜻이 있다. 매든 또는 링크를 클릭합니다. )
기본 사례를 통해 문의:
let array = [1,2,3];
const initialMemo = [];
array = array.reduce((memo, iteratee) => {
// if condition is our filter
if (iteratee > 1) {
// what happens inside the filter is the map
memo.push(iteratee * 2);
}
// this return value will be passed in as the 'memo' argument
// to the next call of this function, and this function will have
// every element passed into it at some point.
return memo;
}, initialMemo)
console.log(array) // [4,6], equivalent to [(2 * 2), (3 * 2)]
더 간결하고 버전:
[1,2,3].reduce((memo, value) => value > 1 ? memo.concat(value * 2) : memo, [])
처음 두 개 이상의 등 필터링됨 sanlight 이트라티 디이브이 않았다. 또한, 그냥 그 자체만으로도 니시알기념 기록하십시오 release. 만들기 위해 선택해제합니다 및 소비자의 관심을 보인다. # 39, & # 39 에서 다시 한 번 통과되는 대로 memo&. 첫 번째 익명 함수 호출, 그리고 반환되었습니다 memo& & # 39, 익명 함수 값을 # 39 에 전달됩니다. 인수 다음 함수.
또 다른 예로는 메모 약간만이라도 되돌릴 수 있는 가장 작은 또는 위한 기본 览侩 荤례 최다 어레이입니다. 예:
[7,4,1,99,57,2,1,100].reduce((memo, val) => memo > val ? memo : val)
// ^this would return the largest number in the list.
예를 들어 자신의 절감하십시오 어떻게 쓸 함수 (이 같은 기능을 지원하는 경우가 많습니다 이러한 이해, 내가 찾을 수):
test_arr = [];
// we accept an anonymous function, and an optional 'initial memo' value.
test_arr.my_reducer = function(reduceFunc, initialMemo) {
// if we did not pass in a second argument, then our first memo value
// will be whatever is in index zero. (Otherwise, it will
// be that second argument.)
const initialMemoIsIndexZero = arguments.length < 2;
// here we use that logic to set the memo value accordingly.
let memo = initialMemoIsIndexZero ? this[0] : initialMemo;
// here we use that same boolean to decide whether the first
// value we pass in as iteratee is either the first or second
// element
const initialIteratee = initialMemoIsIndexZero ? 1 : 0;
for (var i = initialIteratee; i < this.length; i++) {
// memo is either the argument passed in above, or the
// first item in the list. initialIteratee is either the
// first item in the list, or the second item in the list.
memo = reduceFunc(memo, this[i]);
}
// after we've compressed the array into a single value,
// we return it.
return memo;
}
예를 들어, 실제 구현 접속할 수 있지만 이 같은 것을 느낄 수 있는 단순한 인덱스화할 좋겠다 확보하십시오 골자로 거잖나.
[2]: http://code.blog.kylebaker.io/2018/03/16/stack-overflow/ # 성능은 어떨까요?
<! - begin 스니핏: js 숨기십시오: 거짓값 콘솔: 진정한 바벨. > 거짓값 -;
var arr = [1, 2, 3]
// ES5 syntax
arr = arr.filter(function(item){ return item != 3 })
// ES2015 syntax
arr = arr.filter(item => item != 3)
console.log( arr )
끝 - < 스니핏 >;!
단, 모든 브라우저에서 '배열 필터'가 지원되는 것은 아니므로 프로토타입을 제작해야 합니다:
//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;
};
}
이렇게 하면 필요한 모든 메소드를 프로토타이핑할 수 있습니다.