[英]How can I filter a JavaScript array by element first letter?
Let say I want to search the tickers array and return all of the items in the array that start with S and then write them to the sCompanies = [].假设我想搜索 tickers 数组并返回数组中以 S 开头的所有项目,然后将它们写入 sCompanies = []。
Anyone have any idea how I go about this using a for or while loop?任何人都知道我 go 如何使用 for 或 while 循环?
// Iterate through this list of tickers to build your new array:
let tickers = ['A', 'SAS', 'SADS' 'ZUMZ'];
//console.log(tickers);
// Define your empty sCompanies array here:
//Maybe need to use const sComapnies = [] ?
let sCompanies = []
// Write your loop here:
for (i = 0; i < tickers.length; i++) {
console.log(tickers[i]);
}
// Define sLength here:
sLength = 'test';
/*
// These lines will log your new array and its length to the console:
console.log(sCompanies);
console.log(sLength);*/
Why don't you just use the filter function like this?你为什么不像这样使用过滤器 function 呢?
// Only return companies starting by "S"
const sCompanies = tickers.filter((companyName) => companyName.startsWith('S'))
But if you want to do it with a for loop, you can check this:但是如果你想用 for 循环来做,你可以检查一下:
// Iterate through this list of tickers to build your new array: const tickers = ["A", "SAS", "SADS", "ZUMZ"]; //console.log(tickers); // Define your empty sCompanies array here: const sCompanies = []; // Write your loop here: for (let i = 0; i < tickers.length; i++) { tickers[i].startsWith("S") && sCompanies.push(tickers[i]); } // Define sLength here: const sLength = sCompanies.length; /* // These lines will log your new array and its length to the console: */ console.log(sCompanies); console.log(sLength);
with your loop it would be like this:在你的循环中它会是这样的:
for (i = 0; i < tickers.length; i++) {
if (tickers[i].startsWith('S')) {
sCompanies.push(tickers[i]);
}
}
OR a bit more modern或者更现代一点
for (const i in tickers) {
if (tickers[i].startsWith('S')) {
sCompanies.push(tickers[i]);
}
}
Better yet using for...of
which is for looping arrays.更好的是使用
for...of
循环 arrays。
for (const ticker of tickers) {
if (ticker.startsWith('S')) {
sCompanies.push(ticker);
}
}
Or you could do a oneliner like the answer above.或者你可以像上面的答案一样做一个 oneliner。
This would go through the tickers array and if it starts with "S", add it to the sCompanies array.这将 go 通过代码数组,如果它以“S”开头,则将其添加到 sCompanies 数组。
tickers.forEach(function (item, index, array) {
if (item.startsWith('S')) {
sCompanies.push(item);
}
})
I also got the following code back as the model solution, I understood the reason to use this format is incase I wanted to target something other than first letter:我还得到了以下代码作为 model 解决方案,我理解使用这种格式的原因是因为我想针对首字母以外的其他内容:
if(tickers[i][0] == 'S')
Then I could use [1] instead of [0] to target the second letter.然后我可以使用 [1] 而不是 [0] 来定位第二个字母。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.