Javascript에서 배열에서 빈 요소 제거
JavaScript 배열에서 빈 요소를 제거하려면 어떻게 해야 합니까?
간단한 방법이 있습니까?아니면 루프를 반복하여 수동으로 제거해야 합니까?
몇 가지 간단한 방법:
var arr = [1,2,,3,,-3,null,,0,,undefined,4,,4,,5,,6,,,,];
arr.filter(n => n)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Number)
// [1, 2, 3, -3, 4, 4, 5, 6]
arr.filter(Boolean)
// [1, 2, 3, -3, 4, 4, 5, 6]
또는 - ("텍스트" 유형의 단일 배열 항목만 해당)
['','1','2',3,,'4',,undefined,,,'5'].join('').split('');
// output: ["1","2","3","4","5"]
또는 - 기존 방식: 단순 반복
var arr = [1,2,null, undefined,3,,3,,,0,,,[],,{},,5,,6,,,,],
len = arr.length, i;
for(i = 0; i < len; i++ )
arr[i] && arr.push(arr[i]); // copy non-empty values to the end of the array
arr.splice(0 , len); // cut the array and leave only the non-empty values
// [1,2,3,3,[],Object{},5,6]
j쿼리:
var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
arr = $.grep(arr, n => n == 0 || n);
// [1, 2, 3, 3, 0, 4, 4, 5, 6]
편집: 이 질문은 거의 9년 전에 답변되었습니다.그때, 이 질문에 대한 답변은 도움이 되는 임베디드 메서드가 거의 없었습니다.Array.prototype
.
요,그러면좋아요,그러면좋아요.filter
★★★★★★ 。
이 메서드는 제공하는 콜백 함수의 기준을 충족하는 요소를 포함하는 새 어레이를 반환합니다.
를 들어, 「」를 삭제하는 .null
★★★★★★★★★★★★★★★★★」undefined
::
var array = [0, 1, null, 2, "", 3, undefined, 3,,,,,, 4,, 4,, 5,, 6,,,,];
var filtered = array.filter(function (el) {
return el != null;
});
console.log(filtered);
예를 들어 문자열을 취급하는 경우 위의 함수는 빈 문자열인 요소를 제거하지 않습니다.
자주 사용되는 패턴 중 하나는 빈 스트링을 포함한 가짜 요소를 제거하는 것입니다.""
,0
,NaN
,null
,undefined
, , , , 입니다.false
.
해서 '넘어갈 수 있어요.filter
「」, 「」,Boolean
생성자 함수 또는 필터 기준 함수에서 동일한 요소를 반환합니다. 예를 들어 다음과 같습니다.
var filtered = array.filter(Boolean);
또는
var filtered = array.filter(function(el) { return el; });
쪽이든, 이것은 ' 쪽이든', '어느 쪽이든', '어느 쪽이든', '어느 쪽이든', '어느 쪽이든'이기에 효과가 있습니다.filter
는 ""를 합니다.Boolean
하는 함수로서의 , 두 '컨스트럭터', '컨스트럭터', '컨스트럭터', '컨스트럭터', '컨스트럭터', '컨스트럭터',filter
을 method "로으로 변환합니다.Boolean
.
어레이를 하여 " "구멍"을 할 수 .filter
를 들어하는 콜백을 하다
var sparseArray = [0, , , 1, , , , , 2, , , , 3],
cleanArray = sparseArray.filter(function () { return true });
console.log(cleanArray); // [ 0, 1, 2, 3 ]
오래된 답변:이러지 마!
이 방법을 사용하여 네이티브 어레이 프로토타입을 확장합니다.
Array.prototype.clean = function(deleteValue) {
for (var i = 0; i < this.length; i++) {
if (this[i] == deleteValue) {
this.splice(i, 1);
i--;
}
}
return this;
};
test = new Array("", "One", "Two", "", "Three", "", "Four").clean("");
test2 = [1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,];
test2.clean(undefined);
또는 기존 요소를 다른 배열로 푸시할 수도 있습니다.
// Will remove all falsy values: undefined, null, 0, false, NaN and "" (empty string)
function cleanArray(actual) {
var newArray = new Array();
for (var i = 0; i < actual.length; i++) {
if (actual[i]) {
newArray.push(actual[i]);
}
}
return newArray;
}
cleanArray([1, 2,, 3,, 3,,,,,, 4,, 4,, 5,, 6,,,,]);
모든 빈 값("), null, defined 및 0)을 제거해야 하는 경우:
arr = arr.filter(function(e){return e});
빈 값과 줄 바꿈을 제거하려면:
arr = arr.filter(function(e){ return e.replace(/(\r\n|\n|\r)/gm,"")});
예:
arr = ["hello",0,"",null,undefined,1,100," "]
arr.filter(function(e){return e});
반품:
["hello", 1, 100, " "]
UPDATE (Alnitak의 코멘트에 근거)
경우에 따라 어레이에 "0"을 유지하고 다른 항목(null, undefined 및 ")을 삭제할 수 있습니다.이 방법은 다음과 같습니다.
arr.filter(function(e){ return e === 0 || e });
반품:
["hello", 0, 1, 100, " "]
라이너 1개만:
[1, false, "", undefined, 2].filter(Boolean); // [1, 2]
또는 underscorejs.org 를 사용합니다.
_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]
Javascript 1.6 이후를 사용하고 있는 경우, 간단한 사용법을 사용할 수 있습니다.return true
★★★★★★★★★★★★★★★★★★★:
arr = arr.filter(function() { return true; });
.filter
는 원래 배열에서 누락된 요소를 자동으로 건너뜁니다.
에는 MDN의 .filter
정식 버전을 지원하지 않는 JavaScript 인터프리터에서 사용할 수 있습니다.
.null
와 엔트리가 .undefined
OP는 'OP'입니다.
구멍을 제거하기 위해서는
arr.filter(() => true)
arr.flat(0) // New in ES2019
홀 제거, null 및 정의되지 않은 경우:
arr.filter(x => x != null)
홀 제거 및 false(null, undefined, 0, -0, 0n, NaN, "" false, document.all) 값:
arr.filter(x => x)
arr = [, null, (void 0), 0, -0, 0n, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, 0n, NaN, false, '', 42]
console.log(arr.filter(x => x != null)); // [0, -0, 0n, NaN, false, "", 42]
console.log(arr.filter(x => x)); // [42]
주의:
- 홀은 요소가 없는 배열 인덱스입니다.
arr = [, ,];
console.log(arr[0], 0 in arr, arr.length); // undefined, false, 2; arr[0] is a hole
arr[42] = 42;
console.log(arr[10], 10 in arr, arr.length); // undefined, false, 43; arr[10] is a hole
arr1 = [1, 2, 3];
arr1[0] = (void 0);
console.log(arr1[0], 0 in arr1); // undefined, true; a[0] is undefined, not a hole
arr2 = [1, 2, 3];
delete arr2[0]; // NEVER do this please
console.log(arr2[0], 0 in arr2, arr2.length); // undefined, false; a[0] is a hole
- 위의 모든 메서드는 지정된 배열의 복사본을 반환하는 것이지 내부 수정은 반환하지 않습니다.
arr = [1, 3, null, 4];
filtered = arr.filter(x => x != null);
console.log(filtered); // [1, 3, 4]
console.log(arr); // [1, 3, null, 4]; not modified
깔끔한 방법.
var arr = [0,1,2,"Thomas","false",false,true,null,3,4,undefined,5,"end"];
arr = arr.filter(Boolean);
// [1, 2, "Thomas", "false", true, 3, 4, 5, "end"]
아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,ES6+
같다고 합니다.
const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
답은 다음 두 가지 방법 중 하나입니다.
첫 번째 방법:
const clearArray = arr.filter(i => i); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
두 번째 방법:
const clearArray = arr.filter(Boolean); // [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];
console.log("arr.filter(i => i)", arr.filter(i => i));
console.log("arr.filter(Boolean)", arr.filter(Boolean));
ES6:
let newArr = arr.filter(e => e);
심플한 ES6
['a','b','',,,'w','b'].filter(v => v);
언더스코어/Lodash 포함:
일반적인 사용 사례:
_.without(array, emptyVal, otherEmptyVal);
_.without([1, 2, 1, 0, 3, 1, 4], 0, 1);
빈칸 포함:
_.without(['foo', 'bar', '', 'baz', '', '', 'foobar'], '');
--> ["foo", "bar", "baz", "foobar"]
라이브러리를 사용하는 것이 옵션인 경우 compact() http://documentcloud.github.com/underscore/라는 함수가 있는 것으로 알고 있습니다.또한 라이브러리에는 어레이 및 컬렉션과 관련된 기타 유용한 기능도 몇 가지 있습니다.
다음은 그 문서에서 발췌한 것입니다.
_.parray(어레이)
모든 거짓 값이 제거된 배열의 복사본을 반환합니다.JavaScript에서는 false, null, 0, " 정의되지 않음 및 NaN은 모두 거짓입니다.
_.disc([0, 1, false, 2, ' , 3]);
=> [1, 2, 3]
@알니탁
실제로 Array.filter는 코드를 추가하면 모든 브라우저에서 작동합니다.이하를 참조해 주세요.
var array = ["","one",0,"",null,0,1,2,4,"two"];
function isempty(x){
if(x!=="")
return true;
}
var res = array.filter(isempty);
document.writeln(res.toJSONString());
// gives: ["one",0,null,0,1,2,4,"two"]
이것은 IE용으로 추가해야 하는 코드이지만 필터와 기능 프로그래밍의 가치는 imo입니다.
//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;
};
}
하지 않았고 되어 있기 에 여러분은 ''를 사용할 수 ._.without(array, *values);
_.without(["text", "string", null, null, null, "text"], null)
// => ["text", "string", "text"]
배열에서 정의되지 않은 요소를 제거하려면 다음을 사용하십시오.
const array = [
{ name: "tim", age: 1 },
undefined,
{ name: "ewrfer", age: 22 },
{ name: "3tf5gh", age: 56 },
null,
{ name: "kygm", age: 19 },
undefined,
];
console.log(array.filter(Boolean));
어레이의 길이를 변경하는 동안 문제가 발생할 수 있기 때문에 어레이를 루프오버하고 어레이에서 유지하는 아이템을 사용하여 새로운 어레이를 구축하는 것이 권장한 대로 루프 및 스플라이스하는 것보다 더 쉬울 수 있습니다.
다음과 같은 작업을 수행할 수 있습니다.
function removeFalsyElementsFromArray(someArray) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(someArray[index]) {
newArray.push(someArray[index]);
}
}
return newArray;
}
실제로 보다 일반적인 솔루션이 있습니다.
function removeElementsFromArray(someArray, filter) {
var newArray = [];
for(var index = 0; index < someArray.length; index++) {
if(filter(someArray[index]) == false) {
newArray.push(someArray[index]);
}
}
return newArray;
}
// then provide one or more filter functions that will
// filter out the elements based on some condition:
function isNullOrUndefined(item) {
return (item == null || typeof(item) == "undefined");
}
// then call the function like this:
var myArray = [1,2,,3,,3,,,,,,4,,4,,5,,6,,,,];
var results = removeElementsFromArray(myArray, isNullOrUndefined);
// results == [1,2,3,3,4,4,5,6]
다른 유형의 필터 기능을 사용할 수 있다는 것을 알 수 있습니다.필요 이상으로요, 하지만 전 관대함을 느꼈어요...;)
이것은 어떻습니까(ES6) : 배열에서 Falsy 값을 삭제합니다.
var arr = [0,1,2,"test","false",false,true,null,3,4,undefined,5,"end"];
arr.filter((v) => (!!(v)==true));
//output:
//[1, 2, "test", "false", true, 3, 4, 5, "end"]
빈 요소 없이 배열을 가져오려면 필터를 사용해야 합니다.ES6의 예
const array = [1, 32, 2, undefined, 3];
const newArray = array.filter(arr => arr);
위의 가장 높은 투표율을 사용하는 경우, 첫 번째 예에서는 문자열 길이가 1보다 큰 개별 문자를 가져옵니다.그 문제에 대한 저의 해결방법은 다음과 같습니다.
var stringObject = ["", "some string yay", "", "", "Other string yay"];
stringObject = stringObject.filter(function(n){ return n.length > 0});
정의되지 않은 경우 반환되지 않는 대신 길이가 0보다 클 경우 반환됩니다.누군가 도움이 됐으면 좋겠네요
돌아온다
["some string yay", "Other string yay"]
ES5에 제 Array..filter()
'을 하는 것이 만, 'Golf-hack'을 사용하는 것이 .Object
String
,Boolean
, 「」Number
상기와 같이
'ES5'filter()
대해서는 이미.undefined
내의 , 즉 으로 「」, 「」를 반환하는 함수.true
모든 요소를 반환합니다.filter()
, non-time, non-time만 합니다.undefined
★★★★
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(function(){return true})
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
쓰다, 쓰다, 쓰다...(function(){return true;})
보다 ...(Object)
및의 ; 의 반환값Object
어떤 상황에서도 컨스트럭터는 일종의 객체가 됩니다.위에서 제시한 프리미티브박스 컨스트럭터와는 달리 가능한 오브젝트 값은 false이기 때문에 부울 설정에서는Object
의 손이 모자라다function(){return true}
.
> [1,,5,6,772,5,24,5,'abc',function(){},1,5,,3].filter(Object)
[1, 5, 6, 772, 5, 24, 5, 'abc', function (){}, 1, 5, 3]
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })
console.log(r)
[1,2,3]
모든 빈 요소 제거
배열에 빈 개체, 배열 및 문자열이 다른 빈 요소와 함께 포함되어 있는 경우 다음과 같이 제거할 수 있습니다.
const arr = [ [], ['not', 'empty'], {}, { key: 'value' }, 0, 1, null, 2, "", "here", " ", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ]
let filtered = JSON.stringify(
arr.filter((obj) => {
return ![null, undefined, ''].includes(obj)
}).filter((el) => {
return typeof el != "object" || Object.keys(el).length > 0
})
)
console.log(JSON.parse(filtered))
단순한 압축(어레이에서 빈 요소 제거)
ES6의 경우:
const arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
let filtered = arr.filter((obj) => { return ![null, undefined].includes(obj) })
console.log(filtered)
플레인 Javascript 사용 ->
var arr = [0, 1, null, 2, "", 3, undefined, 3, , , , , , 4, , 4, , 5, , 6, , , ,]
var filtered = arr.filter(function (obj) { return ![null, undefined].includes(obj) })
console.log(filtered)
와 함께 할 수 .in
let a = [1,,2,,,3];
let b = a.filter((x,i)=> i in a);
console.log({a,b});
그건 어때?
js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6
다른 방법은 배열의 길이 속성을 활용하는 것입니다. 배열의 '왼쪽'에 늘이 아닌 항목을 포장한 다음 길이를 줄이는 것입니다.이 알고리즘은 메모리를 할당하지 않는 임플레이스 알고리즘으로 가비지 콜렉터에는 적합하지 않습니다.또, 베스트/평균/최악의 케이스 동작도 매우 양호합니다.
이 솔루션은 여기 있는 다른 솔루션과 비교하여 Chrome에서는 2배에서 50배, Firefox에서는 5배에서 50배 더 빠릅니다. http://jsperf.com/remove-null-items-from-array
다음 코드는 열거할 수 없는 'removeNull' 메서드를 어레이에 추가하고 데이지 체인에 대해 'this'를 반환합니다.
var removeNull = function() {
var nullCount = 0 ;
var length = this.length ;
for (var i=0, len=this.length; i<len; i++) { if (!this[i]) {nullCount++} }
// no item is null
if (!nullCount) { return this}
// all items are null
if (nullCount == length) { this.length = 0; return this }
// mix of null // non-null
var idest=0, isrc=length-1;
length -= nullCount ;
while (true) {
// find a non null (source) slot on the right
while (!this[isrc]) { isrc--; nullCount--; }
if (!nullCount) { break } // break if found all null
// find one null slot on the left (destination)
while ( this[idest]) { idest++ }
// perform copy
this[idest]=this[isrc];
if (!(--nullCount)) {break}
idest++; isrc --;
}
this.length=length;
return this;
};
Object.defineProperty(Array.prototype, 'removeNull',
{ value : removeNull, writable : true, configurable : true } ) ;
foo = [0, 1, 2, "", , false, 3, "four", null]
foo.filter(function(e) {
return e === 0 ? '0' : e
})
돌아온다
[0, 1, 2, 3, "four"]
이 기능은 AppJet에서 테스트했습니다(IDE에 코드를 복사하여 붙여넣고 "다시 로드"를 누르면 작동하므로 계정을 만들 필요가 없습니다).
/* appjet:version 0.1 */
function Joes_remove(someArray) {
var newArray = [];
var element;
for( element in someArray){
if(someArray[element]!=undefined ) {
newArray.push(someArray[element]);
}
}
return newArray;
}
var myArray2 = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];
print("Original array:", myArray2);
print("Clenased array:", Joes_remove(myArray2) );
/*
Returns: [1,2,3,3,0,4,4,5,6]
*/
(오브젝트 멤버) 루프에서 for...를 '오용'하고 있습니다.=> 루프 본체에는 truthy 값만 표시됩니다.
// --- Example ----------
var field = [];
field[0] = 'One';
field[1] = 1;
field[3] = true;
field[5] = 43.68;
field[7] = 'theLastElement';
// --- Example ----------
var originalLength;
// Store the length of the array.
originalLength = field.length;
for (var i in field) {
// Attach the truthy values upon the end of the array.
field.push(field[i]);
}
// Delete the original range within the array so that
// only the new elements are preserved.
field.splice(0, originalLength);
도움이 될 수 있습니다.https://lodash.com/docs/4.17.4#remove
var details = [
{
reference: 'ref-1',
description: 'desc-1',
price: 1
}, {
reference: '',
description: '',
price: ''
}, {
reference: 'ref-2',
description: 'desc-2',
price: 200
}, {
reference: 'ref-3',
description: 'desc-3',
price: 3
}, {
reference: '',
description: '',
price: ''
}
];
scope.removeEmptyDetails(details);
expect(details.length).toEqual(3);
scope.removeEmptyDetails = function(details){
_.remove(details, function(detail){
return (_.isEmpty(detail.reference) && _.isEmpty(detail.description) && _.isEmpty(detail.price));
});
};
var data= {
myAction: function(array){
return array.filter(function(el){
return (el !== (undefined || null || ''));
}).join(" ");
}
};
var string = data.myAction(["I", "am","", "working", "", "on","", "nodejs", "" ]);
console.log(string);
출력:
nodejs 작업 중
배열에서 빈 요소를 제거하고 다른 요소를 표시합니다.
언급URL : https://stackoverflow.com/questions/281264/remove-empty-elements-from-an-array-in-javascript
'programing' 카테고리의 다른 글
WHERE 절에서 mysql concat()을 사용하고 있습니까? (0) | 2023.01.15 |
---|---|
Matplotlib tight_layout()은 그림 suptitle을 고려하지 않습니다. (0) | 2023.01.15 |
vuejs - 메서드를 통해 계산된 속성 변경 (0) | 2023.01.15 |
JavaScript 이벤트 클릭을 트리거하려면 어떻게 해야 합니까? (0) | 2023.01.15 |
TextArea에서 줄 바꿈 (0) | 2023.01.15 |