Array foreach() function - javascript

I declared array and added variables inside so now I want to create one click function with javascript but I have no idea how I tried this but not working
function volumeUpDown(){
let a = $('._1');
let b = $('._2');
let c = $('._3');
let d = $('._4');
let e = $('._5');
let f = $('._6');
let g = $('._7');
let ar = [a,b,c,d,e,f,g];
ar.forEach().click(function(){
$(this).addClass('volactive');
})
}
volumeUpDown();

You can do the whole thing in one jQuery call:
$('._1, ._2, ._3, ._4, ._5, ._6, ._7').click(function() {
$(this).addClass("volactive");
});
The comma in the selector string lets you ask for multiple different matches to be collected into the jQuery object. The jQuery object is already an array (sort-of) and jQuery functions like .click() will do their work for all elements in the jQuery object.

Just for dynamic purposes, in case you need to someday add more dynamically (using still a single jQuery call, which is the correct approach anyway)
$(Array.from({length: 7},(_,i) => `._{$i + 1}`).join(', ')).click(function() {
$(this).addClass("volactive")
});
The first part will generate the selector:
const selector = Array.from({length: 7},(_,i) => `._${i + 1}`).join(', ');
console.log(selector);

You need to take the object and apply the callback.
ar.forEach(o => o.click(function() {
$(this).addClass('volactive');
}));

That's not how you use forEach:
ar.forEach(elem => elem.click(function() {
$(this).addClass("volactive");
}));

Related

Does reduce not work with jQuery? How to count elements in a const variable?

I'd like to create a const variable that is equal to the number of checked checkboxes with a certain class. This is my code to do that(which is not working):
const blocksUserAddLineCBs = $(".useradd"+blockIdEnding);
const blocksUserAddLinesActiveCBCounter = blocksUserAddLineCBs.reduce((currentTotal, item) => {
return $(item).prop('checked') === true + currentTotal;
}, 0);
Is the reduce method not working with a Field created with a jQuery Selector? How could i that without having to create a let Variable and a $().each Loop which increases the variable every time it recognizes one of the elements is checked ($(this).prop('checked'))
.reduce doesn't work on jQuery objects, and in any event it's overkill:
const count = $('.useradd' + blockIdEnding + ':checked').length;
or alternatively:
const $els = $('.useradd' + blockIdEnding);
const count = $els.filter(':checked').length;
(variables renamed to prevent window overflow)
reduce is a method found on arrays.
A jQuery object is not an array.
You can get an array from a jQuery object using its toArray method.

Block duplicates when adding to an array in JavaScript

I am beginner in JavaScript. I have this code:
var imageArray = [];
$(document).on("click", ".showPrv", function () {
$("#dropzone").each(function () {
$(".dz-image-preview").each(function () {
$(".dz-image").each(function () {
imageArray.push($(this).find("img").attr("src"))
});
});
});
console.log(imageArray);
})
This code works fine, but I have a problem with duplicates in my array imageArray. How can you block duplicates from being added to this table?
Try to use the includes() function.
Using it will be:
...
$(".dz-image").each(function () {
if(!imageArray.includes($(this).find("img").attr("src")))
imageArray.push($(this).find("img").attr("src"))
});
...
You can check if the value exists in the imageArray before pushing a new one, somewhat like this:
const imgSrc = $(this).find("img").attr("src");
if(!imageArray.includes(imgSrc)) {
imageArray.push(imgSrc);
}
I would recommend using a Set for this, as it allows for a quick lookups (O(1)) in order to check if the value already exists. Using an array forces you to do .includes() which takes O(n) time.
const imageSet = new Set();
...
const imgSrcAttr = $(this).find("img").attr("src");
if(!imageSet.has(imgSrcAttr)) {
imageSet.add(imgSrcAttr);
}
...
If at some point you need to convert the set to an array, you can simply use the spread-operator:
const imageArr = [...imageSet];
If the element was not found, -1 will be returned. Refer to $.inArray():
// If not in your array then
if($.inArray($(this).find("img").attr("src"), imageArray) === -1){
// Add value to imageArray
imageArray.push($(this).find("img").attr("src"));
}
Example of $.inArray() on JSFiddle for better understanding.

localStorage, find the difference within the old and new value

I need to find out the difference in the old and new value of the localStorage when the change event if triggered.
I can toggle the same localStorage key within different tabs, so if I add one the values would be:
'1234,4321'
But then when I remove one it would be:
'1234'
My code below will convert the string to an array, separating the comma. However this only seems to work on way around, so if I remove one the code below will display an empty array, instead of the removed number.
window.addEventListener('storage', function (e) {
if (e.key === 'favourites') {
let newv = e.newValue.split(',').filter(id => !!id);
let oldv = e.oldValue.split(',').filter(id => !!id);
let difference = newv.filter(function (i) {
return oldv.indexOf(i) === -1;
});
console.log(difference);
}
});
What is the best way to do this!?
So you need to check for added by looking to see if the original does not have it from the new values. And to check for a removed item, you need to check that the id does not exist in the orginal values.
const oldValue = '1234,4321'
const newValue = '1234,5555'
const oldValueIds = oldValue.split(",")
const newValueIds = newValue.split(",")
const removed = oldValueIds.filter(id => !newValueIds.includes(id))
const added = newValueIds.filter(id => !oldValueIds.includes(id))
console.log('removed: ', removed)
console.log('added: ', added)

javascript function returning issue

I want to return the var "source" value for all the element, now when I put the "source" out of each function, it become undefined.I want to return the whole source array. How to do that? any help would be truly appreciated -
function _getSource(){
var product = fpd.getProduct(true);
$(product[0].elements).each(function(i, elem) {
var source = elem.parameters['source'];
})
return source;
alert (source);
}
Assuming that you're actually after an array containing the source property of each element:
function _getSource(){
var product = fpd.getProduct(true);
return $(product[0].elements).map(function(i, elem) {
return elem.parameters['source'];
}).get(); // .get() turns jQuery collection into an array
}
.map is a very good replacement for a .each / push combo. It comes from functional languages where the "map" function just takes an array, transmutes each elements, and returns a new array of those transmuted results.
The final .get is not strictly necessary if you don't mind getting an array-like result back rather than a proper array.
When you write var source you are declaring a new variable scoped to the function of the each callback. Declare it outside and get rid of the var so you are just assigning instead of redeclaring, and you probably also want to build up an array and not just assign. Something like this:
function _getSource(){
var product = fpd.getProduct(true);
var sources = [];
$(product[0].elements).each(function() {
sources.push(elem.parameters['source']);
})
return sources;
}
source is only defined inside the each function because you var'd it there.
Try this instead:
function _getSource() {
return $(fpd.getProduct(true)[0].elements).map(function() {return this.parameters['source'];});
}

Remove an element from find return

With the fallowing code I want to delete the last element inside the steps variable,
var steps = $(element).find("fieldset");
var count = steps.size();
steps[count-1] = null;
but when I iterate with the each method, it doesn't seems to see the null value
steps.each(function(i) {
});
Use the slice function
steps = steps.slice(0, -1);
You could use not() to create a new jQuery object removing the elements you don't want:
steps = steps.not(steps.last());

Categories