Supongamos que tengo una matriz sin ningún orden en particular y quiero obtener todos los valores de un tipo dado de esa matriz (para este ejemplo, usemos cadenas).
oldArray = [1, "2", {3: 4}, 5, "6", /7/]; /* ... */ newArray = ["2", "6"];Lógicamente, haría algo como esto:
newArray = []; oldArray.forEach((element) => { if (typeof element === "string") { newArray.push(element); } }); (Aunque no es tan elegante como el one-liner de Python [value for value in oldArray if type(value) == str] , todavía es suficiente para mí).
Mi pregunta es: ¿hay una forma más eficiente de hacer esto o es una solución óptima?
Usando Array#filter y typeof :
const oldArray = [1, "2", {3: 4}, 5, "6", /7/]; const newArray = oldArray.filter(e => typeof e === 'string'); console.log(newArray);Puedes usar array.filter() :
newArray = oldArray.filter(e => typeof e == "string")