2

At the page I have these sections:

<section id="questions-688">
</section>

<section id="test">
</section>

<section id="stats-688">
</section>

<section id="answers-636">
</section>

<section id="someDiv">
</section>

I would like to create an array with these numbers: [688, 636]. So when id of section is started with questions or answers or stats, I want to add number belongs to this ID to array, but ONLY ONCE. How can I do this via javascript?

Here is function which create an array [688, 688, 636], but I need [688, 636].

var selector = 'section[id^=stats-],section[id^=answers-],section[id^=questions-]';
segments = Array.prototype.map.call(document.querySelectorAll(selector), function (section) {
  return section.id.split('-')[1]|0;
});

How can I do this?

user3357400
  • 397
  • 2
  • 9
  • 26
  • See http://stackoverflow.com/q/1960473/218196 – Felix Kling May 10 '14 at 10:44
  • Ideal solution will eventually be to use a Set instead of an array, when ECMAScript 6 eventually becomes standard in all browsers: http://www.nczonline.net/blog/2012/09/25/ecmascript-6-collections-part-1-sets/ – reggoodwin May 10 '14 at 11:05

2 Answers2

1

Simple for-loop with indexOf method will help you:

var sections = document.querySelectorAll('section[id^=stats-],section[id^=answers-],section[id^=questions-]'),
segments = [];

for (var i = 0; i < sections.length; i++) {
    var split = sections[i].id.split('-');
    if (segments.indexOf(split[1]) == -1) {
        segments.push(split[1]);
    }    
}

http://jsfiddle.net/6Fj6Z/

dfsq
  • 191,768
  • 25
  • 236
  • 258
0

The array method indexOf will return the first index the element is found if it exists otherwise a -1 if it does not exist.

var someArray = [688, 636];

if(!someArray.indexOf(688)) {
  someArray.push(688);
}
Sten Muchow
  • 6,623
  • 4
  • 36
  • 46