admin管理员组文章数量:1355542
var ctr;
var lst = ["", "xml", "w1", "w2"];
var ids = [];
ctr = 0;
for (y = 0; y < lst.length; y++) {
if (lst[y].substring(0, 1) === "w") {
ids[y] = lst[y];
ctr = ctr + 1;
}
}
console.log([ids, ctr]);
OUTPUT: [[undefined, undefined, 'w1','w2'], 2]
EXPECTED OUTPUT: [['w1','w2'],2]
What am I doing wrong? The counter returned the number I have expected but why am i getting 2 undefined in my list? Why is this happening?
var ctr;
var lst = ["", "xml", "w1", "w2"];
var ids = [];
ctr = 0;
for (y = 0; y < lst.length; y++) {
if (lst[y].substring(0, 1) === "w") {
ids[y] = lst[y];
ctr = ctr + 1;
}
}
console.log([ids, ctr]);
OUTPUT: [[undefined, undefined, 'w1','w2'], 2]
EXPECTED OUTPUT: [['w1','w2'],2]
What am I doing wrong? The counter returned the number I have expected but why am i getting 2 undefined in my list? Why is this happening?
Share Improve this question edited Sep 30, 2015 at 2:50 splucena asked Sep 30, 2015 at 2:46 splucenasplucena 1591 gold badge3 silver badges15 bronze badges 1-
What you are actually getting is
[[,,'w1','w2'], 2]
, i.e. there are no members at indexes 0 and 1. Console developers seem to have forgotten how to write elisions (or rely on toString when perhaps they should not).. – RobG Commented Sep 30, 2015 at 3:24
5 Answers
Reset to default 5You need to use ids.push(lst[y]);
instead of ids[y] = lst[y];
, otherwise you will be assigning values to the ids
array at random indexes - ie missing some index values.
In your code the values are assigned at indexes 2 and 3 missing indexes 0 and 1 causing the said output, it is because you are not assigning values to ids
in all iterations - you are skipping some iterations based on the condition
You can just use a filter to get the items you want and maybe use the output array length to know how many items you have after filtering the original array.
var newArr = ["", "xml", "w1", "w2"].filter(function(x) {
x.substring(0, 1) === 'w');
};
console.log([newArr, newArr.length]); // [["w1", "w2"], 2]
var lst = ["", "xml", "w1", "w2"];
var result = lst.reduce(function (x, y) {
if (y.substring(0, 1) === 'w') {
x[0] || (x[0] = []);
x[0].push(y);
x[1]++ || (x[1] = 1);
}
return x;
}, []);
console.log(result) // [["w1","w2"],2]
The result will be same as required, interesting to note here i use null coalescing notation ||
more info about it here
Suggested by @FelixKing
changing the accumulator
lst.reduce(function (x, y) {
if (y.substring(0, 1) === 'w') {
x[0].push(y);
x[1]++;
}
return x;
}, [[], 0]);
If you want to take a different approach, using reduce will also work:
var res = lst.reduce(function(prevVal, curVal){
if (curVal.substring(0, 1) === "w") {
prevVal[0].push(curVal);
prevVal[1] = prevVal[1] + 1;
}
return prevVal;
}, [[], 0]);
console.log(res); //--> [['w1', 'w2'], 2]
I remend it simply because avoiding for loops whenever possible makes for much more maintainable code, especially in Javascript where the vars used in the for loop condition itself are still members of the parent scope (i.e. they're accessible throughout the entire containing function, with a value of undefined given to them until the initialization value is given in the for loop).
Also, it prevents you from having to juggle index values in your head, and instead concentrate on what the loop is actually doing.
(My above example definitely could be cleaner, but it should give you an idea)
Using existing js
, try substituting ctr
for y
inside if
statement
var ctr;
var lst = ["", "xml", "w1", "w2"];
var ids = [];
ctr = 0;
for (y = 0; y < lst.length; y++) {
if (lst[y].substring(0, 1) === "w") {
ids[ctr] = lst[y];
ctr = ctr + 1;
}
}
console.log([ids, ctr]);
alternatively , using Array.prototype.toString()
, String.prototype.match()
var lst = ["", "xml", "w1", "w2"]
, ids = lst.toString().match(/w./g);
console.log(ids);
本文标签: Filter list with substring javascriptStack Overflow
版权声明:本文标题:Filter list with substring javascript? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1743997029a2573178.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论