Lets say you have a situation where you get 3 numbers from different sources, I wanna merge them together in 1 array and came up with this. Its almost do the trick but I can't combine the numbers into 1 array
$(n + " " + 'ul').each(function(){
var arr = ( $(this).children('li').size());
var test = (""+arr).split("");
console.log(test)
});
//Outcome in console
"1"
"2"
"3"
//Outcome in console what I need
"1, 2, 3"
Something about this line isn't right, I know the split doesn't work but I can't come up with something better to achieve the result.
var test = (""+arr).split("");
4 Answers 4
If you want to have the result as one single string (and not an array), I would use map and then join the result:
var n = "div";
var res = $(n + " " + 'ul').map(function(){
return $(this).children('li').length; // size() is deprecated
}).get().join(", ");
alert(res); // "1, 2, 3"
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="one">
<ul>
<li></li>
</ul>
</div>
<div class="two">
<ul>
<li></li>
<li></li>
</ul>
</div>
<div class="three">
<ul>
<li></li>
<li></li>
<li></li>
</ul>
</div>
Comments
Should it be something like this? You are creating a new array every loop through there:
var test = [];
$(n + " " + 'ul').each(function(){
test.push($(this).children('li').size());
});
console.log(test)
Comments
Use:
$(n + " " + 'ul').each(function(){
var arr = ( $(this).children('li').size());
var test = arr.toString();
});
console.log(test);
Comments
You should look at Array join
var arr = [];
$(n + " " + 'ul').each(function(){
arr.push($(this).children('li').size()));
});
var test = arr.join(", ");
console.log(test);
.size()doesn't return an array, it returns a number. I don't understand what you're doing with that.