Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript loop through list items and return the results in an array

Tags:

javascript

I have been trying to loop through an unordered list of numbers with javascript. The function should store all of the numbers in an array so I can find which numbers are duplicates. Any help would be appreciated. So far I have:

    <html>
<head>
    <title></title>
</head>
<body>
<ul id="ul">
    <li>6</li>
    <li>3</li>
    <li>1</li>
    <li>4</li>
    <li>7</li>
    <li>4</li>
    <li>2</li>
    <li>8</li>
    <li>9</li>
    <li>2</li>
</ul>
</body>
</html>

and a start on the javascript:

(function(){

            var nums = document.getElementById("ul");
            var listItem = nums.getElementsByTagName("li");

            var newNums = "";

            var dups = function(){
            for (var i = 0; i < listItem.length; i++){

            }

            }; dups();

            })();

what am I missing?

like image 906
jmccommas Avatar asked Dec 12 '13 18:12

jmccommas


People also ask

Can you loop through an array in JavaScript?

If we want to loop through an array, we can use the length property to specify that the loop should continue until we reach the last element of our array. In the loop above, we first initialized the index number so that it begins with 0 .

How do I traverse a list in JavaScript?

JavaScript does not offer any specific in-built function to traverse the array elements/objects. You can traverse an array simply using for loop or directly by element index. An array contains multiple elements of the same type, which can be traverse using for loop.


1 Answers

var nums = document.getElementById("ul");
var listItem = nums.getElementsByTagName("li");

var newNums = [];

for (var i=0; i < listItem.length; i++) {
    newNums.push( parseInt( listItem[i].innerHTML, 10 ) );
}

FIDDLE

To not get duplicated values you can do

for (var i=0; i < listItem.length; i++) {
    var num = parseInt( listItem[i].innerHTML, 10 );
    if (newNums.indexOf(num) === -1) {
        newNums.push( num );
    }
}

FIDDLE

And to also get an array with the values that appear more than once

var newNums   = [],
    duplicate = [];

for (var i=0; i < listItem.length; i++) {
    var num = parseInt( listItem[i].innerHTML, 10 );
    if (newNums.indexOf(num) === -1) {
        newNums.push( num );
    }else{
        duplicate.push( num );
    }
}

FIDDLE

Array.indexOf might not be supported in all browsers, but there's a polyfill over at MDN

like image 89
adeneo Avatar answered Sep 22 '22 09:09

adeneo