문제

JavaScript의 배열에서 빈 요소를 어떻게 제거합니까?

간단한 방법이 있습니까, 아니면 반복하여 수동으로 제거해야합니까?

도움이 되었습니까?

해결책

편집하다: 이 질문은 거의 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 메소드는 내부적으로 콜백의 반환 값을 암시 적으로 Boolean.

희소 배열로 작업하고 있고 "구멍"을 제거하려는 경우 간단히 사용할 수 있습니다. filter 예를 들어 True를 반환하는 콜백을 전달하는 메소드 :

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,,,,]);

다른 팁

간단한 방법 :

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

arr // [1,2,3,3,[],Object{},5,6]


jQuery를 통해 :

var arr = [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,];

arr = $.grep(arr,function(n){ return n == 0 || n });

arr // [1, 2, 3, 3, 0, 4, 4, 5, 6]


업데이트 - 또 다른 빠르고 멋진 방법 (ES6 사용) :

var arr = [1,2,null, undefined,3,,3,,,0,,,4,,4,,5,,6,,,,], 
    temp = [];

for(let i of arr)
    i && temp.push(i); // copy each non-empty value to the 'temp' array

arr = temp;
delete temp; // discard the variable

arr // [1, 2, 3, 3, 4, 4, 5, 6]

빈 값을 제거하십시오

['foo', '',,,'',,null, ' ', 3, true, [], [1], {}, undefined, ()=>{}].filter(String)

// ["foo", null, " ", 3, true, [1], Object {}, undefined, ()=>{}]

빈 값을 모두 제거 해야하는 경우 ( "", NULL, UNDEFINED 및 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, " "]

업데이트 (Alnitak의 의견 기반)

어떤 상황에서는 배열에서 "0"을 유지하고 다른 것을 제거하고 싶을 수도 있습니다 (NULL, UNDEFINED 및 ""). 이것은 한 가지 방법입니다.

arr.filter(function(e){ return e === 0 || e });

반품:

["hello", 0, 1, 100, " "]

단순히 하나의 라이너 :

[1, false, "", undefined, 2].filter(Boolean); // [1, 2]

또는 사용 alterscorejs.org:

_.filter([1, false, "", undefined, 2], Boolean); // [1, 2]
// or even:
_.compact([1, false, "", undefined, 2]); // [1, 2]

JavaScript가 1.6 이상인 경우 사용할 수 있습니다. Array.filter 사소한 사용 return true 콜백 함수, 예를 들어 :

arr = arr.filter(function() { return true; });

~부터 .filter 원래 배열에서 누락 된 요소를 자동으로 건너 뜁니다.

위에 링크 된 MDN 페이지에는 멋진 오류 확인 버전도 포함되어 있습니다. filter 공식 버전을 지원하지 않는 JavaScript 통역사에서 사용할 수 있습니다.

이것은 제거되지 않습니다 null 명시 적으로 항목이나 항목 undefined 값이지만 OP는 구체적으로 "누락 된"항목을 요청했습니다.

구멍을 제거하려면 사용해야합니다

arr.filter(() => true)
arr.flat(0) // Currently stage 3, check compatibility before using this

구멍을 제거하고 거짓 (null, null, undefined, 0, -0, nan, ", false, document.all) 값 :

arr.filter(x => x)

구멍을 제거하기 위해, null 및 정의되지 않은 :

arr.filter(x => x != null)

arr = [, null, (void 0), 0, -0, NaN, false, '', 42];
console.log(arr.filter(() => true)); // [null, (void 0), 0, -0, NaN, false, '', 42]
console.log(arr.filter(x => x)); // [42]
console.log(arr.filter(x => x != null)); // [0, -0, NaN, false, "", 42]

깨끗한 방법.

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

['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"]

보다 없이 Lodash 문서.

단지 ES6 최신 버전 방법은 배열이 다음과 같습니다.

 const arr = [1,2,3,undefined,4,5,6,undefined,7,8,undefined,undefined,0,9];

간단한 방법 :

 const clearArray = arr.filter( i => i );

라이브러리를 사용하는 것이 옵션이라면 indercore.js는 compact ()라는 함수가 있습니다. http://documentcloud.github.com/underscore/ 또한 배열 및 컬렉션과 관련된 몇 가지 다른 유용한 기능이 있습니다.

다음은 문서에서 발췌 한 내용입니다.

_.compact (배열)

모든 거짓 값이 제거 된 배열 사본을 반환합니다. JavaScript에서, false, null, 0, "", 정의되지 않은 및 Nan은 모두 거짓입니다.

_.compact ([0, 1, false, 2, '', 3];

=> [1, 2, 3]

@alnitak

추가 코드를 추가하면 실제로 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"]

배열을 반복하고 배열에서 루프를 유지하는 동안 배열과 스플 라이스를 시도하는 것보다 배열에서 보관하려는 항목에서 새 배열을 만들기가 더 쉽다는 것을 알 수 있습니다. 끝이 문제를 일으킬 수 있습니다.

당신은 다음과 같은 일을 할 수 있습니다 :

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: let newArr = arr.filter(e => e);

이는 어떻습니까 (ES6) : 배열에서 허위 값을 제거합니다.

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);

나는 단순히 위의“Call ES5 's에 내 목소리를 더하고 있습니다. Array..filter() 글로벌 생성자 "Golf-Hack이지만 사용하는 것이 좋습니다. Object 대신에 String, Boolean, 또는 Number 위에서 제안한대로.

구체적으로, ES5 filter() 이미 트리거되지 않습니다 undefined 배열 내의 요소; 따라서 보편적으로 반환되는 기능 true, 반환 모두 집단 filter() 히트, 반드시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 생성자는 아래에 있습니다 모든 상황, 일종의 대상. 위에서 제안한 원시적 박스-구성 요소와 달리, 가능한 객체 가치는 거짓이 아니며, 따라서 부울 환경에서는 없습니다. 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]

위의 가장 높은 투표 답변을 사용할 때 첫 번째 예, 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"]
var data = [null, 1,2,3];
var r = data.filter(function(i){ return i != null; })

console.log(r) 

[1,2,3]

그게 어때 :

js> [1,2,,3,,3,,,0,,,4,,4,,5,,6,,,,].filter(String).join(',')
1,2,3,3,0,4,4,5,6

이 작동, 나는 그것을 테스트했다 appjet (IDE에서 코드를 복사하고 "Reload"를 눌러 작동하는 것을 확인할 수 있습니다. 계정을 만들 필요가 없습니다).

/* 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]
*/

이를 수행하는 또 다른 방법은 배열의 길이 속성을 활용하는 것입니다. 배열의 '왼쪽'에 널이 아닌 항목을 포장 한 다음 길이를 줄입니다. 그것은 현장 알고리즘으로 메모리를 할당하지 않고 쓰레기 수집가에게 너무 나쁘고, 최고/평균/최악의 행동을 가지고 있습니다.

이 솔루션은 여기의 다른 솔루션에 비해 Chrome에서 2 ~ 50 배 더 빠르며 Firefox에서는 5 ~ 50 배 더 빠릅니다. http://jsperf.com/remove-null-items-from-array

아래 코드는 배열에 취소 할 수없는 'removenull'메소드를 추가하여 Daisy-Chaining을 위해 '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"]

'오도 사용'the ... in (Object-Member) 루프. => 루프 본문에는 진실 값 만 나타납니다.

// --- 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에서 일하고 있습니다

배열에서 빈 요소를 제거하고 다른 요소를 표시합니다.

정규 표현식으로 유효하지 않은 항목을 필터링합니다

array = array.filter(/\w/);
filter + regexp

빈 요소를 제거하는 가장 좋은 방법은 사용하는 것입니다. Array.prototype.filter(), 다른 답변에서 이미 언급했듯이.

안타깝게도, Array.prototype.filter() IE <9에 의해 지원되지 않습니다. IE8 또는 이전 버전의 IE를 지원 해야하는 경우 다음을 사용할 수 있습니다. 폴리 필 지원을 추가합니다 Array.prototype.filter() 이 브라우저에서 :

if (!Array.prototype.filter) {
  Array.prototype.filter = function(fun/*, thisArg*/) {
    'use strict';
    if (this === void 0 || this === null) {
      throw new TypeError();
    }
    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== 'function') {
      throw new TypeError();
    }
    var res = [];
    var thisArg = arguments.length >= 2 ? arguments[1] : void 0;
    for (var i = 0; i < len; i++) {
      if (i in t) {
        var val = t[i];
        if (fun.call(thisArg, val, i, t)) {
          res.push(val);
        }
      }
    }
    return res;
  };
}

누군가가 전체 배열이나 물체를 청소하려는 경우 도움이 될 수 있습니다..

var qwerty = {
    test1: null,
    test2: 'somestring',
    test3: 3,
    test4: {},
    test5: {
        foo: "bar"
    },
    test6: "",
    test7: undefined,
    test8: " ",
    test9: true,
    test10: [],
    test11: ["77","88"],
    test12: {
        foo: "foo",
        bar: {
            foo: "q",
            bar: {
                foo:4,
                bar:{}
            }
        },
        bob: {}
    }
}

var asdfg = [,,"", " ", "yyyy", 78, null, undefined,true, {}, {x:6}, [], [2,3,5]];

function clean_data(obj) {
    for (var key in obj) {
        // Delete null, undefined, "", " "
        if (obj[key] === null || obj[key] === undefined || obj[key] === "" || obj[key] === " ") {
            delete obj[key];
        }
        // Delete empty object
        // Note : typeof Array is also object
        if (typeof obj[key] === 'object' && Object.keys(obj[key]).length <= 0) {
            delete obj[key];
        }
        // If non empty object call function again
        if(typeof obj[key] === 'object'){
            clean_data(obj[key]);
        }
    }
    return obj;
}

var objData = clean_data(qwerty);
console.log(objData);
var arrayData = clean_data(asdfg);
console.log(arrayData);

산출:

무엇이든 제거합니다 null, undefined, "", " ", empty object 또는 empty array

jsfiddle 여기

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top