vacios remover especifico eliminar elementos elemento asociativo arreglo array javascript arrays node.js

remover - eliminar un elemento especifico de un array javascript



Eliminar elementos vacĂ­os de una matriz en Javascript (30)

¿Cómo elimino elementos vacíos de una matriz en JavaScript?

¿Hay alguna forma directa o tengo que recorrerlo y eliminarlos manualmente?


Maneras sencillas:

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]

o - (solo para elementos de una sola matriz de tipo "texto")

['''',''1'',''2'',3,,''4'',,undefined,,,''5''].join('''').split(''''); // output: ["1","2","3","4","5"]

o - Forma clásica: iteración simple.

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]


a través de 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]


ACTUALIZACIÓN - solo otra manera rápida y fresca (usando 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]

Eliminar valores vacíos

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


"Mal uso" del bucle for ... in (object-member). => Sólo los valores de verdad aparecen en el cuerpo del bucle.

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


¿Qué hay de eso?

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


@Alnitak

En realidad, Array.filter funciona en todos los navegadores si agrega algún código adicional. Vea abajo.

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

Este es el código que debe agregar para IE, pero el filtro y la programación funcional vale la pena.

//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; }; }


Como nadie más lo mencionó y la mayoría de las personas han incluido un guión bajo en su proyecto, también puede utilizar _.without(array, *values); .

_.without(["text", "string", null, null, null, "text"], null) // => ["text", "string", "text"]


Cuando usé la respuesta más votada arriba, primer ejemplo, obtuve caracteres individuales para longitudes de cadena mayores que 1. A continuación, se encuentra mi solución para ese problema.

var stringObject = ["", "some string yay", "", "", "Other string yay"]; stringObject = stringObject.filter(function(n){ return n.length > 0});

En lugar de no regresar si no está definido, regresamos si la longitud es mayor que 0. Espero que ayude a alguien por ahí.

Devoluciones

["some string yay", "Other string yay"]


Debe usar el filtro para obtener una matriz sin elementos vacíos. Ejemplo en ES6

const array = [1, 32, 2, undefined, 3]; const newArray = array.filter(arr => arr);


ES6 simple

[''a'',''b'','''',,,''w'',''b''].filter(v => v);


ES6: permite que newArr = arr.filter (e => e);


Es posible que le resulte más fácil realizar un bucle en su matriz y crear una nueva matriz a partir de los elementos que desea mantener de la matriz que intentar un bucle y empalme como se ha sugerido, ya que se modifica la longitud de la matriz mientras se realiza un bucle El sobre puede introducir problemas.

Podrías hacer algo como esto:

function removeFalsyElementsFromArray(someArray) { var newArray = []; for(var index = 0; index < someArray.length; index++) { if(someArray[index]) { newArray.push(someArray[index]); } } return newArray; }

En realidad aquí hay una solución más genérica:

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]

Usted tiene la idea, entonces podría tener otros tipos de funciones de filtro. Probablemente más de lo que necesitas, pero me sentía generoso ...;)


Este solo eliminará los valores vacíos y no los falsos, lo que creo que es más deseable.

Hay una opción para eliminar también los valores nulos.

Este método debería ser mucho más rápido que usar el empalme.

function cleanArray(a, removeNull) { var i, l, temp = []; l = a.length; if (removeNull) { for (i = 0; i < l; i++) { if (a[i] !== undefined && a[i] !== null) { temp.push(a[i]); } } } else { for (i = 0; i < l; i++) { if (a[i] !== undefined) { temp.push(a[i]); } } } a.length = 0; l = temp.length; for (i = 0; i < l; i++) { a[i] = temp[i]; } temp.length = 0; return a; } var myArray = [1, 2, , 3, , 3, , , 0, , null, false, , NaN, '''', 4, , 4, , 5, , 6, , , , ]; cleanArray(myArray); myArray;


Esto funciona, lo probé en AppJet (puede copiar y pegar el código en su IDE y presionar "recargar" para que funcione, no es necesario crear una cuenta)

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


Esto podría ayudarlo a usted: 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)); }); };


Filtrado de entradas inválidas con una expresión regular

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


La forma limpia de hacerlo.

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


La mejor manera de eliminar elementos vacíos es usar Array.prototype.filter() , como ya se mencionó en otras respuestas.

Desafortunadamente, Array.prototype.filter() no es compatible con IE <9. Si aún necesita compatibilidad con IE8 o una versión aún más antigua de IE, puede usar el siguiente polyfill para agregar compatibilidad con Array.prototype.filter() en estos navegadores:

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


Otra forma de hacerlo es aprovechar la propiedad de longitud de la matriz: empacar los elementos que no sean nulos en la ''izquierda'' de la matriz y luego reducir la longitud. Es un algoritmo in situ (no asigna memoria, que es muy malo para el recolector de basura), y tiene un comportamiento muy bueno / promedio / peor de los casos.

Esta solución, en comparación con otras aquí, es de 2 a 50 veces más rápida en Chrome y de 5 a 50 veces más rápida en Firefox, como puede ver aquí: http://jsperf.com/remove-null-items-from-array

El siguiente código agrega el método no enumerable ''removeNull'' al Array, que devuelve ''this'' para el encadenamiento en margarita:

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


Para remover agujeros, debes usar

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

Para eliminar los valores de agujero, y, falsy (nulo, indefinido, 0, -0, NaN, "", false, document.all):

arr.filter(x => x)

Para quitar el agujero, nulo e indefinido:

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]


Si necesita eliminar TODOS los valores vacíos ("", nulo, indefinido y 0):

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

Para eliminar valores vacíos y saltos de línea:

arr = arr.filter(function(e){ return e.replace(/(/r/n|/n|/r)/gm,"")});

Ejemplo:

arr = ["hello",0,"",null,undefined,1,100," "] arr.filter(function(e){return e});

Regreso:

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

ACTUALIZACIÓN (basado en el comentario de Alnitak)

En algunas situaciones, es posible que desee mantener "0" en la matriz y eliminar cualquier otra cosa (null, undefined y ""), esta es una forma:

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

Regreso:

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


Si tiene Javascript 1.6 o posterior, puede usar Array.filter usando una función de devolución de llamada return true trivial, por ejemplo:

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

ya que .filter omite automáticamente los elementos que faltan en la matriz original.

La página MDN enlazada anteriormente también contiene una buena versión de filter de comprobación de errores que se puede usar en intérpretes de JavaScript que no son compatibles con la versión oficial.

Tenga en cuenta que esto no eliminará null entradas null ni las entradas con un valor undefined explícito, pero el OP solicitó específicamente las entradas "faltantes".


Si usar una biblioteca es una opción, tengo entendido que underscore.js tiene una función llamada compacta () http://documentcloud.github.com/underscore/ también tiene otras funciones útiles relacionadas con matrices y colecciones.

Aquí hay un extracto de su documentación:

_.compact (array)

Devuelve una copia de la matriz con todos los valores falsos eliminados. En JavaScript, falso, nulo, 0, "", indefinido y NaN son falsos.

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

=> [1, 2, 3]


Simplemente estoy agregando mi voz a la anterior "llame a ES5''s Array..filter() con un constructor global" golf-hack, pero sugiero usar Object lugar de String , Boolean o Number como se sugirió anteriormente.

Específicamente, el filter() ES5 ya no dispara para elementos undefined dentro de la matriz; por lo tanto, una función que devuelve universalmente true , que devuelve todos los elementos filter() , necesariamente solo devolverá elementos no 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]

Sin embargo, escribir ...(function(){return true;}) es más largo que escribir ...(Object) ; y el valor de retorno del constructor de Object será, bajo cualquier circunstancia , algún tipo de objeto. A diferencia de los constructores de boxeo primitivos sugeridos anteriormente, ningún valor-objeto posible es falsey y, por lo tanto, en una configuración booleana, Object es una mano corta para 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]


Simplemente un trazador de líneas:

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

o utilizando underscorejs.org :

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


Solo ES6 y el método de las versiones más recientes, se supone que la matriz está debajo:

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

Manera simple:

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


¿Qué pasa con esto (ES6): Para eliminar el valor de Falsy de una matriz.

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


Con subrayado / Lodash:

Caso de uso general:

_.without(array, emptyVal, otherEmptyVal); _.without([1, 2, 1, 0, 3, 1, 4], 0, 1);

Con vacíos:

_.without([''foo'', ''bar'', '''', ''baz'', '''', '''', ''foobar''], ''''); --> ["foo", "bar", "baz", "foobar"]

Vea la documentación de lodash para sin .


EDITAR: Esta pregunta fue respondida hace casi 9 años, cuando no había muchos métodos incorporados útiles en el Array.prototype .

Ahora, ciertamente te recomendaría que uses el método de filter .

Tenga en cuenta que este método le devolverá una nueva matriz con los elementos que pasan los criterios de la función de devolución de llamada que le proporciona, por ejemplo, si desea eliminar valores null o 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);

Dependerá de lo que considere "vacío", por ejemplo, si estaba tratando con cadenas, la función anterior no eliminaría los elementos que son una cadena vacía.

Un patrón común que veo que se usa con frecuencia es eliminar elementos falsos , que incluyen una cadena vacía "" , 0 , NaN , null , undefined y false .

Simplemente puede pasar al método de filter , a la Boolean constructora Boolean , o simplemente devolver el mismo elemento en la función de criterios de filtro, por ejemplo:

var filtered = array.filter(Boolean);

O

var filtered = array.filter(function(el) { return el; });

En ambos sentidos, esto funciona porque el método de filter en el primer caso llama al constructor Boolean como una función, convirtiendo el valor, y en el segundo caso, el método de filter convierte internamente el valor de retorno de la devolución de llamada implícitamente a Boolean .

Si está trabajando con matrices dispersas, y está tratando de deshacerse de los "agujeros", simplemente puede usar el método de filter pasando una devolución de llamada que devuelve true, por ejemplo:

var sparseArray = [0, , , 1, , , , , 2, , , , 3], cleanArray = sparseArray.filter(function () { return true }); console.log(cleanArray); // [ 0, 1, 2, 3 ]

Antigua respuesta: ¡No hagas esto!

Utilizo este método, extendiendo el prototipo nativo Array:

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

O simplemente puede empujar los elementos existentes en otra matriz:

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


Si alguien está buscando limpiar todo el Array u Objeto, esto podría ayudar .

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

Salida:

Elimina todo lo que sea null , undefined , "" , " " , empty object empty array o empty array

jsfiddle here


foo = [0, 1, 2, "", , false, 3, "four", null] foo.filter(function(e) { return e === 0 ? ''0'' : e })

devoluciones

[0, 1, 2, 3, "four"]


var data = [null, 1,2,3]; var r = data.filter(function(i){ return i != null; })

console.log(r)

[1,2,3]