remove all elements in array with .remove() [closed] - javascript

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
This question does not appear to be about programming within the scope defined in the help center.
Closed 8 years ago.
Improve this question
So I have an array of numbers, let's say ["1", "3", "2"]
they correspond to values of the data-cardNumber attribute I've given to certain elements.
I want all elements with the data-cardNumber values in the array to be removed.
I tried doing this by iterating through the array and constructing a selector per each item in the array that calls .remove(), but that doesn't work.
I think the selector is too complex since it spans multiple strings.
How can I iterate through the array and .remove() all elements with the data-cardNumber attribute whose values are in the array?
Here is the code that I tried:
for(var i=0; i<swipedAwayCards.length; i++){
$('[data-cardNumber="'+swipedAwayCards[i]'"]').remove();
// i'm trying to construct a selector like [data-cardNumber="1"]
}

Looks like it's just a syntax error, which should have shown up in console:
$('[data-cardNumber="'+swipedAwayCards[i]+'"]')
(You missed the final + in your concatenation).

You could try the following:
$('[data-cardNumber="'+swipedAwayCards[i] + '"]').each(function() {
$(this).remove();
});
This should work rather than doing a for loop since jquery already has the capability to iterate over all matches of a selector.

You may need to do either of the the Following
var a = [1,2,3,4];
for(var i = 0 ; i< a.length; i++){
delete(a[i]); // This resets the value to undefined
}
which produces the following result
[undefined, undefined, undefined, undefined]
or
var a = [1,2,3,4];
var b;
for(var i = 0 ; i< a.length; i++){
b = a.pop();// This actually removes the Element from array and puts it in the variable b
}
Result: ** b = 1 At last as last element to be popped will be 1 and b = []**

Related

Find unique prefix and remove from array of string [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 4 years ago.
Improve this question
In Javascript, given an array of strings, how to find the unique prefix of all the strings and then remove that prefix from each string.
For example:
["05098701", "05012302", "0545621", "0509301"]
unique prefix would be "05"
resultant array would be
["098701", "012302", "45621", "09301"]
You need to search like a human does: check with one char, then with two and so on..
Then just remove the prefix from every item from the array.
You can do this using map method by passing a callback function.
array = ["05098701", "05012302", "0545621", "0509301"]
function longestCommonPrefix(arr){
// sort() method arranges array elements alphabetically
var sortArr = arr.sort();
// Get first array element
var arrFirstElem = arr[0];
// Get the last array element length minus one
var arrLastElem = sortArr[sortArr.length - 1];
// Get first array element length
var arrFirstElemLength = arrFirstElem.length;
// Set "i" incrementer to 0
var i= 0;
// while "i" is less than the length of the first array element AND
// the first array element character position matches the last array character position
// increment "i" by one
while(i < arrFirstElemLength && arrFirstElem.charAt(i) === arrLastElem.charAt(i)) {
i++;
}
//return the prefix
return arrFirstElem.substring(0, i);
}
prefix = longestCommonPrefix(array);
array = array.map(function(item){
return item.substring(prefix.length, item.length);
});
console.log(array);

Type error, cannot read property 'match' of undefined [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 5 years ago.
Improve this question
i got stuck in the Javascript code below, I don't know what's the problem.
the code is always showing"Type error, cannot read property 'match' of undefined",
Here IS THE CODE:
function keepletteronly(str) {
str=str.toLowerCase();//Make the string to lower case
arr=str.split(""); //This way I make an array out of the string
arr1=[]; //make an new array
for (i=1; i<=arr.length;i++){
if (arr[i].match(/[a-z]/)!=null) { //This is where the problem is
arr1.push(arr[i]); //retain only the letters and append to the arr1
}
}
newstring=arr1.join;
return newstring;
}
keepletteronly("1eye");
The index of a JS array starts from zero.
You should change your for sentence to
for ( i = 0; i < arr.length; i += 1) {
Moreover, another sentence is also incorrect:
newstring=arr1.join;
it should be
newstring=arr1.join('');
or simply produce the resultant string without arr1, like:
newstring='';
...
newstring+=arr[i];
Arrays in Javascript are base 0, meaning the first item is at index 0. Imagine you have three items in an array, the length property will say 3 and the three items will occupy indices 0, 1 and 2.
In your for loop, you start at index 1 (i=1;), meaning the loop will skip the first item (at index 0) and then you iterate while i is lower or equal to the length of the array. The length of the array is 3, but because of base 0, the last item in the array is at index 2. So in the last iteration of your for loop, you try to access index 3 of the array, which is undefined.
So, what you need to do is to change your for loop expressions to look like this:
(i = 0; i < arr.length; i++)
This way you will properly iterate over 0, 1 and 2 instead of 1, 2 and 3

Where does this undefined value come from? [closed]

Closed. This question is not reproducible or was caused by typos. It is not currently accepting answers.
This question was caused by a typo or a problem that can no longer be reproduced. While similar questions may be on-topic here, this one was resolved in a way less likely to help future readers.
Closed 6 years ago.
Improve this question
I am trying to compare two arrays and return a new array with any items only found in one of the two given arrays.
e.g. Result of comparing [1,2,3,4] and [1,2,3] should be: [4].
Problem is that, I get 'undefined' element after loop is executed.
function diff(arr1, arr2){
var newArr = [];
for(i=arr1[0]; i<=arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
console.log(newArr);
};
diff([1,2,3,4], [1,2,3]);
result of this is [4, undefined]. What am i doing wrong?
Your for loop has been defined incorrectly. It should start at i=0 and run until i<arr1.length
function diff(arr1, arr2){
var newArr = [];
for(i=0; i<arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
console.log(newArr);
};
By running until i<=arr1.length you are attempting to iterate once more than is needed, resulting in the addition of the final undefined value in the results array. As Mario Garcia says in comments, in the final iteration the loop will try to access arr[4] which doesn't exist, so is therefore undefined.
Your loop is wrong because your iterator doesn't start from 0 (to match the first array element), but from the value of the array at the index zero (which is number 1 in your case, but could be pretty much anything); and then you go out of index range when the iterator reaches the length of an array, in your case it's 4, and arr1[4] is undefined.
After fixing the loop start value and condition, we get:
function diff(arr1, arr2){
var newArr = [];
for(i = 0; i < arr1.length; i++){
if(arr2.indexOf(arr1[i])=== -1){
newArr.push(arr1[i]);
}
}
alert(newArr);
};
diff([1,2,3,4], [1,2,3]); // 4
diff([1,2,3,4,5], [1,3]); // 2, 4, 5

Increase performance for array manipulation [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 years ago.
Improve this question
I am using as certain code in JavaScript where I have to append a huge amount of data such as 10000 objects at a time to an array, and in a click event I again empty that array and reload that array with 10000 objects. Here is my code snippet:
where "Nodes" is an array populated from user datasource.
var Index = 0;
var _array = new Array();
for (var i = 0; i < this.Nodes.length; i++) {
if(this.Nodes.PLeft>this.Nodes.Cleft){
var temp = {};
temp["PLeft"] = this.Nodes.PLeft;
temp["CLeft"] = this.Nodes.CLeft;
temp["PWidth"] = this.Nodes.PWidth;
temp["CWidth"] = this.NodesCWidth;
temp["PTop"] = this.Nodes.PTop;
temp["CTop"] = this.Nodes.CTop;
temp["Height"] = this.Nodes.Height;
_array[Index++] = temp;
}
}
This works fine with Firefox, but for IE and Chrome the performance is too bad -- sometimes the browser crashes. I have also used push() method for array, but I did not find much difference in the performance. Does anyone have any idea on how to improve performance of array manipulation?
A few issues here. First, your loop does not access the individual elements of this.Nodes. Because you keep referring to this.Nodes.PLeft (for example), you wind up with the same probably-undefined value. You must specify the index, this.Nodes[idx].PLeft.
This, of course, begs the question: why do you need to loop some array and turn it into... an array? Can't you just use this.Nodes directly instead of transferring it all into _array first?
Another thing: to reduce the weight of a loop, get the max length outside of the loops conditional statement. Doing it within the conditional causes that value to be looked up every time, by putting it into a variable the lookup only happens once.
You can eliminate the temp object and add the new array element directly. Likewise, you can eliminate the redundant counter and use the for... loop's counter.
var _array = [];
var maxlen = this.Nodes.length;
for (var idx = 0; idx < maxlen ; idx++) {
if(this.Nodes[idx].PLeft > this.Nodes[idx].Cleft){
// use idx for the array key IF you want it to match with this.Nodes indexes
// if you don't care, use _array.length
_array[_array.length] = {
'PLeft':this.Nodes[idx].PLeft,
'CLeft':this.Nodes[idx].CLeft,
'PWidth':this.Nodes[idx].PWidth,
'CWidth':this.Nodes[idx].CWidth,
'PTop':this.Nodes[idx].PTop,
'CTop':this.Nodes[idx].CTop,
'Height':this.Nodes[idx].Height
};
}
}

JavaScript regex match id in innerHTML [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
I managed to get all the text with .innerHTML, code should match all IDs which have pattern: sens[number] Is it possible to get the number? Is there some way around? And please no jQuery, thank you!
Preamble
Don't try to look for elements from the innerHTML string. Strings are hard to parse, and the DOM makes it really easy to search for elements with specific properties. With that said:
General Solution
// grab all elements on the page and setup an array to store matches
var els = document.getElementByTagName('*').
results = [];
// iterate over the elements
for (var i = 0; i < els.length; i++){
// see if the element has an id and, if so, if it matches
// the "sens[number]" pattern
if (els[i].id && /sens\[\d+\]/.test(els[i].id)){
// found a match, add it to results
results.push(els[i]);
}
}
Modern Solution
Of course you can also use querySelectorAll and look for [id^="sens["][id$="]"], but this can be problematic on older browsers (IE < 8).
var els = document.querySelectorAll('[id^="sens["][id$="]"]'),
results = [];
for (var i = 0; i < els.length; i++){
// all we've found are elements that start with "sens[" and
// end with a "]". We still need to verify there's a number
// between the brackets ([])
if (/sens\[\d+\]/.test(els[i].id)){
results.push(els[i]);
}
}
If you are simply trying to get the elements that have a similar id
var elements = document.querySelectorAll('[id^="sens[number]"]');
^= will match any id starting with sens[number]
if number is supposed to be dynamic
var elements = document.querySelectorAll('[id^=sens]');
grabs all that start with sens or you could use a variable with the selector to get a specific ones with a number
var number = 1;
var elements = document.querySelectorAll('[id^=sens"['+number+']"]');

Categories

Resources