在不使用sort()的情况下获取HTML LI元素的副本

时间:2015-03-20 14:06:59

标签: javascript

假设你有这样的事情:

<ul>
    <li>4</li>
    <li>1</li>
    <li>3</li>
    <li>6</li>
    <li>3</li>
    <li>8</li>
    <li>9</li>
    <li>5</li>
</ul>

然后问题是使用JavaScript找到第一个副本但是你不能使用sort()方法。

你会怎么做?

5 个答案:

答案 0 :(得分:2)

只需将对象用作Hashmap:

// Values is an an hashmap storing all the values that have already been seen
var values = {};

// Get all the nodes
var nodes = document.getElementsByTagName("ul")[0].childNodes;


// Iterate over all the nodes, and check if its content has already been seen    
for (var node in nodes) {

  // If the hashmap already has a key equal to the innerHTML of the node return the current node
  if (values[node.innerHTML])
    return node;

  // Else set the hashmap key
  values[node.innerHTML] = true;
});

使用ECMAScript 6,您将能够以更实用的方式执行此操作:

nodes.find(function (node) {

  if (values[node.innerHTML])
    return true;

  values[node.innerHTML] = true;
  return false;
});

答案 1 :(得分:1)

伪代码:

var found = {};
for each li in lis {
    if (found[li.textContent]) {
        // found a duplicate!
    }
    found[li.textContent] = true;
}

答案 2 :(得分:0)

ul转换为数组:

var list = [].slice.call(document.getElementsByTagName('ul')[0].childNodes).map(function (li) {
   return li.innerText;
})

执行此功能以统一列表:

 /**
  * @param list Mutable source
  * @return a list of duplicated indexes
  */
function uniqify(list) {
   var duplicatesIndexes = [];
   var b = list.length;
   while(c = --b) {
      while(c--) {
         if (list[b] === list[c]) {
            list.splice(c, 1); // Remove first duplicate
            duplicatesIndexes.push(c); // Save index of duplicte
         }
      }
   }

   return duplicatesIndexes;
}

查看结果:

var list = [1, 1, 3, 6, 3, 8, 9, 5, 5, 5];
uniqify(list);
// <- [8, 7, 2, 0]
console.log(list);
// <- [1, 6, 3, 8, 9, 5]

如果您想对重复的li s执行某些操作:

var liList = [].slice.call(document.getElementsByTagName('ul')[0].childNodes);
uniqify(list).forEach(function (index) {
   liList[index].style.borderColor = 'red';
});

答案 3 :(得分:-1)

我会遍历li项并将其值添加到集合中。然后,您可以检查该值是否在集合中。

答案 4 :(得分:-2)

checkedArray = [];
elem = document.getElementsByTagName("li"); /* Would be better to have a direct reference to a specific element */
for(var i = 0; i < elem.length; i++) {
    var currentValue = elem[i].innerHTML;
    if(checkedArray.indexOf(currentValue) != -1) {
        // Found
    }
    checkedArray.push(currentValue);
}