Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

116
Vistas
Javascript: How to remove empty string values from an array?

I have this array of objects:

const data = [{
    "_id": "plastic",
    "countries": ['Egypt','','Iran','',''],
    "likelihood": [1,2,3,4,5],
    "relevance": [1,2,3,4,5],
    "intensity": [1,2,3,4,5]
},
{
    "_id": "peak oil",
    "countries": ['USA','Russia',''],
    "likelihood": [1,2,3],
    "relevance": [1,2,3],
    "intensity": [1,2,3]
 }]

I want to remove empty strings in the countries array. Now here's the catch, I want to remove the same index in likelihood,relevance and intensity as well.

I tried this:

// replacement for splice, array.remove(index)
Array.prototype.remove = function(from, to) {
        var rest = this.slice((to || from) + 1 || this.length);
        this.length = from < 0 ? this.length + from : from;
        return this.push.apply(this, rest);
      };
    
data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

Example output on the above data:

[{
        "_id": "plastic",
        "countries": ['Egypt','Iran'],
        "likelihood": [1,3],
        "relevance": [1,3],
        "intensity": [1,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia'],
        "likelihood": [1,2],
        "relevance": [1,2],
        "intensity": [1,2]
 }]

As you can see the index which was empty in the countries array was removed along with likelihood,relevance,intensity.

How can I achieve this ?

UPDATE

I want multiple strings to be removed.

about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

to remove, you can use splice

const datas=[{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }];

for (const i in datas){
    const rmIdx=datas[i]["countries"].findIndex(val=>val==="");
    for (const key of ["countries","likelihood", "relevance","intensity"]){
        datas[i][key].splice(rmIdx,1)
    }
}

console.log(datas)
about 4 years ago · Juan Pablo Isaza Denunciar

0

Your code works. Can't say it's the cleanest approach, but it correctly removes the values.

Array.prototype.remove = function(from, to) {
  var rest = this.slice((to || from) + 1 || this.length);
  this.length = from < 0 ? this.length + from : from;
  return this.push.apply(this, rest);
};

const data = [{
        "_id": "plastic",
        "countries": ['Egypt','','Iran'],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
    },
    {
        "_id": "peak oil",
        "countries": ['USA','Russia',''],
        "likelihood": [1,2,3],
        "relevance": [1,2,3],
        "intensity": [1,2,3]
 }]

data.forEach(obj => {
  obj.countries.forEach((country, index) => {
    if (country === "") {
      obj.countries.remove(index)
      obj.likelihood.remove(index)
      obj.relevance.remove(index)
      obj.intensity.remove(index)
    }
  })
})

console.log(data);

However, in your code, you are directly editing Array.prototype. This is a bad practice and can cause issues in the future. Instead, you can directly use Array.splice to remove the items.

EDIT: This now remove all instances of empty strings

const data = [{
    "_id": "plastic",
    "countries": ['Egypt', '', 'Iran', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  },
  {
    "_id": "peak oil",
    "countries": ['', 'USA', 'Russia', ''],
    "likelihood": [1, 2, 3, 4],
    "relevance": [1, 2, 3, 4],
    "intensity": [1, 2, 3, 4]
  }
]

const cleaned = data.map(thing => {
  while (thing.countries.includes('')) {
    const index = thing.countries.indexOf('');
    thing.countries.splice(index, 1);
    thing.likelihood.splice(index, 1);
    thing.relevance.splice(index, 1);
    thing.intensity.splice(index, 1);
  }
  return thing;
})

console.log(cleaned);

about 4 years ago · Juan Pablo Isaza Denunciar

0

Replace

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.remove(index)
            obj.relevance.remove(index)
            obj.intensity.remove(index)
          }
        })
      })

with

data.forEach(obj => {
        obj.countries.forEach((country,index) => {
          if (country === "") {
            obj.countries.remove(index)
            obj.likelihood.splice(index) // Using splice is enough.
            obj.relevance.splice(index)
            obj.intensity.splice(index)
          }
        })
      })
about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda