isbn de-duplicate with javascript/jquery - javascript

Brief background: I retrieve book info from google books and worldcat via each api. I parse through the data to create an html div outputs with stuff of interest for a webapp.
The problem: the isbns. After getting isbns from each, I merge them into one div. For example:
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
I would like to eliminate the duplicate isbn (e.g., 9781137012920) with either javascript or jquery. I can get the text of the span but every solution I have tried has failed thus far.
Any help - esp, with a codepen or fiddle - for this amateur would be greatly appreciated.
PS:I know variations of this question have been addressed on StackOverflow - and believe me that I am sick of duplicates! - but I have not managed to fix this after a couple of days of trying. Examples that type in the content as var work but how do I get it from the div and make it work?

Do something like this using text() method with callback
$('span').text(function(i, v) { // use callback to get old value
return v.split(' ') // split the old value
.filter(function(v1, i, arr) { // v1 is array element, i is index, arr is iterating array
return arr.indexOf(v1) == i; // filter unique value by checking the index
}).join(' ') // join and return the unique values
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<span id='tada'>9781137012920 9780230339118 9781137012920 1137012927</span>
For more about finding unique array element refer : Remove Duplicates from JavaScript Array

I suggest removing the duplicates before making them into the div. If you are getting the values in an array you can eliminate the duplicates easily. Remove Duplicates from JavaScript Array

I think you want something like this :
var string = $('span').text();
var uniqueList=string.split(' ').filter(function(allItems,i,a){
return i==a.indexOf(allItems);
}).join(' ');
$('#output').append(uniqueList);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.0.0/jquery.min.js"></script>
<div>
<h1>Input</h1>
<span>9781137012920 9780230339118 9781137012920 1137012927</span>
</div>
<div id="output">
<h1>Becomes</h1>
</div>

Related

How to get a specific class from a classlist array in a clean way?

I faced a problem today, i tooks me hours to just know what it is, so I had an element, this element had many classes :
<div id="myId" class="first second iwantthisone fourth"></div>
I was using a class from the list to pass it as a parameter in an other function, so to get it I was doing this :
const myClass = document.getElementById('myId').classList[2];
Why did I choose 2 ? because when I was doing a console.log to the classList, it was giving me an array ( not regular array ) and the result was like this :
['first', 'second', 'iwantthisone', 'fourth']
So I thought I have finished, I deployed my work to a server, I went there to test if everything is okay, it was not and that's why I am here, so the problem is that the order of the items in the array changed to this :
['second', 'iwantthisone','first', 'fourth']
So my old code in longer working, I need to do this :
const myClass = document.getElementById('myId').classList[1];
Which is not practical, I need to get the class using a method like filter for array, but it seems like I can't use it because classList is not a regular as I mentionned before.
Any solution ?
ANy help would be much appreciated.
You can use filter as long as you converted it from array using Array.from(). I'm skeptical that this is what youre looking for due to the discussion in the comments but from the question alone, this is the solution.
const myClassList = document.getElementById('myId').classList;
var classList = Array.from(myClassList).filter(word => word == "iwantthisone");
console.log(classList);
console.log(myClassList);
<div id="myId" class="first second iwantthisone fourth"></div>

Problems selecting a div depending on text inside

i've been working on a project with puppeteer and it was going great so far until a tried to localize div's depending on their text.
I can't use the div id, name or class, i need to find it by the text inside of it.
My idea is to create an array of all the text i need to find and then loop trought the div's to find the ones that match any of the text in the array.
Can anybody help me find a solution? Thank you!
This is relatively straightforward using vanilla javascript (no JS libraries):
// Get an array of all <divs>:
let allDivs = [... document.getElementsByTagName('div')];
// Loop through allDivs, checking the text of each one:
allDivs.forEach((div) => {
let textInsideDiv = div.textContent;
// THE REST OF YOUR CODE HERE
// if (myArrayOfText.indexOf(textInsideDiv) > -1)) { etc.}
}

JQuery get all data attributes from a list

I have a long dynamically generated list each with the same class identifier and a data attribute similar to the code below:
<ul>
<li class="list" data-id="123">One</li>
<li class="list" data-id="124">Two</li>
<li class="list" data-id="125">Three</li>
<li class="list" data-id="126">Four</li>
.....etc
</ul>
what I am trying to achieve is to get all the data-id values and format them in as follows:
123|124|125|126....etc
this would be then passed to a page via ajax and the id's checked for existence in a database.
var delimited_data="";
$('.list').each(function(){
delimited_data+=$(this).data('id')+"|";
});
console.log(delimited_data);
The reason I am asking this question is that I am working on a live system that automatically deploys items in the list columns to different users after 10 mins. I just need to be sure that the code is going the right way :)
I also need to check that is there are no .list classes on the page (ie - no way to do the query) whether delimited_data will be totally empty which I am pretty sure it would be.
Is there a better way than using .each() in this case as I find it can be rather slow baring in mind that the above function will be run every 30 seconds.
You can use .map to return an array:
var dataList = $(".list").map(function() {
return $(this).data("id");
}).get();
console.log(dataList.join("|"));
Demo: http://jsfiddle.net/RPpXu/
Use this:
var array = [];
$('li.list').each(function() {
array.push($(this).data('id'));
})
var joined = array.join('|');
Not an answer to your question but this is what i ended up on this page in search for and though it would help someone else :-)
var arrayOfObj = $('input').map(function() {
return {
name : $(this).attr('name'),
data : $(this).data('options'),
value : $(this).val(),
id : $(this).attr('id')
}
}).get();
console.log(arrayOfObj)
This returns an array of objects that mimics the input
Cheers!
as an update for #tymeJV answer for new versions of JavaScript you can use .map((index, elem) => return value) like this:
let result = $(".list").map((index, elem) => elem.dataset.id).get().join('|');

how can I assign object properties to dynamic elements based on the modulus operator

I have created a mini template that holds and <h2> & <h3>, I have created a loop that adds .inner everytime i%2 === 0, what i would like to do is split up the data being outputted to follow the same kind of rule so when i%2 === 0 add .inner and also split the object properties so each .inner should display 2 templated object properties. Can anyone advise on how this can be achieved? Also my templated items seem to return undefined?
Demo here http://jsbin.com/otirax/13/edit
Your code can be improved in many ways. The selector here:
$('.inner').append(temp);
should actually be $(".inner:last"), otherwise it affects all ".inner" objects created so far. Better yet, save a newly created div in a variable:
inner = $('<div class="inner"></div>').appendTo($('#ctn'));
and then simply use the var, thus saving an expensive selector operation:
inner.append(...);
Another improvement is to automate template rendering. Consider the following function: it populates arbitrary {{tags}} from an object:
function render(template, values) {
return template.replace(
/{{(\w+)}}/g,
function($0, $1) { return values[$1] });
}
Complete example: http://jsbin.com/iviziz/2/edit
. Let us know if you have questions.
Templated items seem to return undefined:
var temp = template.replace(/name/ig, data.name)
.replace(/age/ig, data.age);
Should be as below due to them being an array.
var temp = template.replace(/name/ig, data[i].name)
.replace(/age/ig, data[i].age);
I assume that thesonglessbird's reply was clear enough, but just to give a proper answer, instead of
var temp = template.replace(/\{\{name\}\}/ig, data.name)
.replace(/\{\{age\}\}/ig, data.age);
you would need to have
var temp = template.replace(/\{\{name\}\}/ig, data[i].name)
.replace(/\{\{age\}\}/ig, data[i].age);
you can see an example here http://jsbin.com/otirax/16/edit
Aside of that, schemantically a 'template' should not be placed inside script tags as it isn't a script.

handling js arrays with jQuery

I am wanting to store some info in array
i declared an array
var added = [];
Question: I want to add a number/string at the last of the array.
And then i want to add all the data to the a dom ?
I am new to js array please help me out with this basic things
added.push("123");
added.push("abc");
$('div').html(added.join());
This will set the html of the div to 123,abc
added.push("123");
added.push("abc");
added.push("xyz");
for(i in added)
{
$("div").append(added[i]);
}
Hope this helps!
EDIT:
I though you need to assign all one by one!
You could use:
$("div").html(added.join(', '));
to get things seperated by comma!

Categories