admin 管理员组文章数量: 1086019
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 badges2 Answers
Reset to default 10Using 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")
版权声明:本文标题:Is there an efficient way to get all values of a certain type from an array in JavaScript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://roclinux.cn/p/1744023383a2520206.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论