简体   繁体   中英

Is there an efficient way to get all values of a certain type from an array in JavaScript?

Suppose that I have an array in no particular order, and I want to get all values of a given type from that array (for this example, let's use strings).

oldArray = [1, "2", {3: 4}, 5, "6", /7/];
/* ... */
newArray = ["2", "6"];

Logically, I would do something like this:

newArray = [];
oldArray.forEach((element) => {
  if (typeof element === "string") {
    newArray.push(element);
  }
});

(Though it isn't as elegant as the Python one-liner [value for value in oldArray if type(value) == str] , it still suffices for me.)


My question is: Is there a more efficient way to do this, or is this an optimal solution?

您可以使用array.filter()

newArray = oldArray.filter(e => typeof e == "string")

Using Array#filter and typeof :

 const oldArray = [1, "2", {3: 4}, 5, "6", /7/]; const newArray = oldArray.filter(e => typeof e === 'string'); console.log(newArray);

我认为这是最简单的你会得到🤣

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM