1

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("");
2
  • .size() doesn't return an array, it returns a number. I don't understand what you're doing with that. Commented Aug 27, 2015 at 13:37
  • Yes I know but it takes the UL and takes the amount of list items from 1 single UL Commented Aug 27, 2015 at 13:39

4 Answers 4

3

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>

Sign up to request clarification or add additional context in comments.

Comments

2

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

1

Use:

    $(n + " " + 'ul').each(function(){
        var arr = ( $(this).children('li').size());
        var test = arr.toString();
    });
    console.log(test);

Comments

1

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

2 Comments

arr is not an array, you can't use .join on it.
@Barmar updated my answer. I thought of just idea last time.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.