最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin1浏览0评论

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?

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?

Share Improve this question asked Nov 2, 2021 at 21:02 wibbuffeywibbuffey 1189 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

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

You can use array.filter():

newArray = oldArray.filter(e => typeof e == "string")
发布评论

评论列表(0)

  1. 暂无评论