Function filter() in jquery - javascript

I study jquery, but i have a little confusion about this code :
var list = mylist.filter(function(f) {
return $(f)
.find('.anthing')
.length > 0;
});
what does $(f) mean?

Your mylist is an array or array like object. The f in the parameters is the single item in your myList.It calls the function for every item in the myList.Then it wraps your f into jQuery object and then the .find() will be visible on your object

It is the index passed through the function, which indicates the
0-based position of the element within the unfiltered set of matched
elements.
In your case $(f) is useless since it represent $(0) || $(1) which does not represent a selection.

Related

New to JavaScript: Can I pass a List into this function and have it still work?

As the title says, I'm new to JavaScript and not completely sure on certain syntax's.
After looking for a while I found the following function:
function makeUL(array) {
// Create the list element:
var list = document.createElement('ul');
for (var i = 0; i < array.length; i++) {
// Create the list item:
var item = document.createElement('li');
// Set its contents:
item.appendChild(document.createTextNode(array[i]));
// Add it to the list:
list.appendChild(item);
}
// Finally, return the constructed list:
return list;
}
All I need to know is if I pass a List of Strings into the functions parameter, will it still work, or when it says array is that defining what kind of variable it is? If it won't currently work with a List what needs to change?
You can pass any Array or Array-like object containing string items, no matter how the parameter is named, and your function will work as expected.
Array-like object is an object, that has a length property with value >=0 and properties 0..length-1. Array-like object offen does not implement Array methods. The Array can be distinguished from Array-like object using a instanceof Array or Array.isArray(a), while the typeof a returns 'object' in both cases.
when it says array is that defining what kind of variable it is?
No. It is defining the name of the variable that the argument will be assigned to in the scope of the function.
JavaScript (at least ES5 which you are using here) doesn't have any type enforcement for function arguments, so you can pass whatever values you like.
The function does expect the value you pass to be an object with a length property and a number of properties with names that are integers (i.e. it expects the value to be like an array (see also duck typing)).
List is not a standard JavaScript data type. If you have created a List object, then you can pass it so long as it is array-like.
arrayis just the name of the expected parameter.
It can be of any type (Javascript doesn't have types)
So: Yes, your list will still "work" (as long as it supports the functions that are called on it, of course)
It will still work. Truly speaking in javascript there is an array no list as such. Hence even if you call the function with below arguments:
makeUL(["Cpp","Java","Javascript"])
The output would be :
<ul>
<li>Cpp</li>
<li>Java</li>
<li>Javascript</li>
</ul>
I'm assuming you mean Array. but i think your function is just returning a DOM element, so you wont directly see that in browser unless you append it into DOM tree.
var listofstrings = ['item 1','item 2','item 3'];
document.getElementByName('body').appendChild(makeUL(listofstring));

jquery exclude array elements

I have an array of elements which I want to maintain efficiently, adding and removing arrays of elements over time.
var myElements = $('.initial');
jquery's merge() seems perfect for adding items as it doesn't create a new array and just adds to the existing one:
$.merge(myElements, $('.to-add'));
Is there an equivalent for removing, that also modifies the array in-place? Something like:
$.exclude(myElements, $('.to-remove'));
I do actually have arrays of DOM elements, and the selectors are just used as examples.
Assuming that you're after the relative complement of b in a.
And you don't want to create additional objects while process.
The function is for both plain Array and jQuery set.
(thus used $.each, $.inArray instead of Array.prototype.forEach Array.prototype.indexOf)
I wrote a function that fits your requirement.
$.exclude = function(a,b) {
var idx;
$.each(b, function(i, val) {
while((idx = $.inArray(val, a)) !== -1) {
a.splice(idx, 1);
}
})
return a;
}
test this code here
https://jsfiddle.net/happyhj/uwd4L1dm/8/
and you can use like this.
$.exclude(myElements, $('.to-remove'));
use jquery not method,
var filtered = $(myElements).not($('.to-remove'));
You can use delete to remove an element from an array and then use $.grep to remove the empty space.
//[0] since $("#id") will be a jquery Object
//[0] will return the particular DOM element
var orgArray = [$("#merge1")[0],$("#merge2")[0],$("#merge3")[0]];
var secArray = [$("#merge4")[0],$("#merge5")[0]]
// Will merge other two values;
// jQuery merge will merge contents of
//two array into first array
var merArray = $.merge(secArray, orgArray);
// Want to remove $("#merge2");
var getIndex = merArray.indexOf($("#merge2")[0]);
if(getIndex >-1){
delete merArray[getIndex]
}
// length before filtering
$("#l1").text(merArray.length);
//Now will remove Empty Space
merArray = $.grep(merArray,function(n){
return n==0 || n
});
$("#l2").text(merArray.length);
JSFIDDLE
You are using methods that are meant for array literals. jQuery already has method add() which will return a modified jQuery object that includes the elements matching the selector
var myElements = $('.initial');
var newCollection = myElements.add('.to-add');
newCollection.not('.to-remove').doSomething();
Don't think of jQuery objects as arrays although they are array like.
Reference add()
It's not clear what your overall objective really is but most likely you can manage it with any number of filtering methods that already exist within the api

why document.getElementsByClassName("className") returns object

I have a some dom objects that are selected with :
var elems = document.getElementsByClassName("royal") ;
and also another objects
var collapsedElems = document.getElementsByClassName("collapsed");
my problem occured when i tried to concat elems and collapsedElems with array concat() method
elems.concat(collapsedElems)
but the return type of getElementsByClassName() is not array actually it is
object. I checked it at chrome console with typeof operator. that seems weird to me how can i combine this two group of object. ?
getElementsByClassName() returns an HTMLcollection object which is similar to an array but not really an array so you can't call array methods using the returned value.
One hack is to use Array's prorotype methods along with .call()/.apply() to pass the returned object as the context.
var elems = document.getElementsByClassName("royal") ;
var collapsedElems = document.getElementsByClassName("collapsed");
var earray = Array.prototype.slice.call(elems, 0);
var concatenated = earray.concat.apply(earray, collapsedElems) ;
console.log(concatenated)
Demo: Fiddle
It returns an HTML Collection which does things that arrays do not (such as getting live updates when the DOM changes).
If you want to get an array with elements from both collections in it, then you could:
Create an array and then populate it by looping over each of the collections and pushing each member into it (which will give you an array) or
Use document.querySelectorAll(".royal, .collapsed"); (gets a NodeList)
From the MDN:
Returns an array-like object of all child elements which have all of
the given class names. When called on the document object, the complete
document is searched, including the root node. You may also call
getElementsByClassName() on any element; it will return only elements
which are descendants of the specified root element with the given
class names.
You can try this:
function getElementsByClassName(className)
{
if (document.getElementsByClassName)
{
return document.getElementsByClassName(className);
}
else
{
return document.querySelectorAll('.' + className);
}
}

How can you find and delete a section of an array with a parameter of a string?

How can you find a section of a JS array and delete it? What I mean is a function that can find a string, looks at an array, sees if one of the "sections" are exactly like the string, and deletes that "section". Here's what I have:
var array = ['a1','f4'];
function findAndDelete(string){
delete array.find('a1');
}
When I try it, nothing happens. It seems that there's a syntax error. How do I fix this?
var array = ['a1','f4'];
function findAndDelete(string){
var index = array.indexOf(string);
if (index > -1) {
array.splice(index, 1);
}
}
Here we can use splice() method of array to delete specific element from it.
This should work
var array = ['a1','f4'];
var index = array.indexOf('a1');
if (index > -1) {
array.splice(index, 1);
}
splice will actually return a new array containing elements which were removed.
Use this:
function findAndDelete(array, string){
if(array.indexOf(string) !== -1) array.splice(array.indexOf(string), 1);
}
var array = ['a1', 'f4'];
findAndDelete(array, 'a1');
JSON.stringify(array); // ['f4'];
a couple of things are happening here:
array.indexOf finds the numeric index of the value (in this case 0 is the index because array[0] == 'a1')
(If the value is not found the index returned will be -1)
array.splice uses the index to delete the item located at that index, the second numer specifies how many elements to delete from there.
There are two possible solutions to this problem, depending on what you want to get out of the function. The first solution will work well if there is only ever one element in the array that matches the string, of it you only want to delete the first element that matches. The second solution will delete all instances of the string passed into the function.
Delete the First Element to Match the String Passed In
The solution that I found to delete one element that matches your passed in string is to use the array.indexOf() method, test the value from that method and, if the index returns a value other than -1, then to pass the index to splice and delete the element from the array. My code is as follows:
var array = ['a1','f4'];
function findAndDelete(arg){
var testString = arg;
var index = array.indexOf(testString); //cache index
if(index !== -1){
array.splice(index,1);
}
}//end findAndDelete()
Once a string is passed into the function, it is stored in the testString variable. Then, we call array.indexOf(testString) and cache the value returned by the function in the index variable. This value is cached to optimize the script and to keep the code DRY (Don't Repeat Yourself). The value of index is then tested to see if it is anything other than -1. The reason index is tested against -1 is because, if the string passed into indexOf() does not exist, the function will return -1. So, if index is not -1, we know that the string passed in exists in the array. The index of that value is then passed to splice as the first argument, which tells where to begin the splice in the array. The second argument passed into splice is the number of element to delete from the array. Since we are only deleting one element of the array, we always pass 1.
You could also create a function that loops through the array with a for-loop and checks every element against the testString. This will work just as well, but is going to be a less efficient way of solving your problem if there will only ever be one element in the array that could match the string you are passing into the function.
Deleting All Instances of the String Passed In
However, the solution I listed above will not work if there are two identical string in the array. For example, if array=['a1','f4','a1'], the function will only delete the first element that it finds. So, after running the function with an argument of 'a1' the array will be: array=['f4','a1']. If you want to be able to delete all elements of an array that match the string you have input, the for-loop solution will work best. The following code would work if you want to delete all elements of an array that match your input:
var array = ['a1','f4', 'a1'];
function findAndDelete(arg){
var testString = arg;
for(var i = 0; i< array.length; i++){
if(testString === array[i]){
array.splice(i,1);
}
}//end for-loop
}//end findAndDelete()
Additionally, if the script is running on IE 8 or older, the indexOf() method will not work. You will need to use the for-loop solution or look for another way to solve your problem.
You are using find() incorrectly. The function you want is indexOf().
IndexOf() returns the index of the value you give it. So you just need to replace
delete array.find('a1');
with
delete array[array.indexOf('a1')];
Note that this only removes the first instance of it.

call a function with a specific index value of nodelist

Is it possible to call a function on specific index value of nodelist which is storing div like following :
var txtElem = txtdiv.getElementsByTagName("div");
the thing i want is that i am storing list of divisions in txtElem nodelist now i want to call a function on click event of the 3rd div stored in nodelist. The divisions are created dynamically and they don't have any id so they are not accessible by id.
from what you asked, it seems like this will do:
function toPseudoArray(nodeList) {
var ar = [];
for(var i in nodeList)
if(nodeList[i].nextSibling) // or for that case any other way to find if this is an element
ar.push(nodeList[i]);
return ar;
}
Pass your nodeList to this function, use what it returns as an array that contains your elements, and only your elements.
By the way, you could directly call function on a specific element simply using my_fab_function(txtElem[0]); -- of course, until you don't exceed the count.
The question is quite unclear. Seeing the jQuery tag, these come to my mind:
A way to call a jQuery function on a specified index using .eq():
var n = 1; //the index you need
$(txtElem).eq(n).css('color', 'red');
Simple Javascript to get the DOM element:
var n = 1; //the index you need
var elem = txtElem[n]; //elem will hold the DOM element
//call simple DOM methods on it:
var s = elem.innerHTML;
//you can also call jQuery functions on it:
$(elem).css('color', 'red');
By the way txtElem is not an object, it is a NodeList, an "array-like object".

Categories