Where does this undefined value come from? [closed] - javascript

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

Related

Why is this code giving me an output of 5? [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 last year.
Improve this question
The goal of this code is to double each number in the array. I was trying to mimic the map() method. But that is not important. What I am wondering is why this code gives me an output of 5 while I did not console.log it. Then when I run it again it keeps adding 5 to a variable I am not aware of?
const numbers = [1, 2, 3, 4, 5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i += 1) {
doubleNumbers.push(numbers[i] * 2)
}
It is because Array.push returns the new length of the array:
let arr = [];
console.log(arr.push('something')) // Should output 1
console.log(arr.push('something else')) // Should output 2
You didn't log anything, but if you run code in the console it will print the outcome of the last statement.
From the documentation: the push() method adds one or more elements to the end of an array and returns the new length of the array.
If you run this in the developer console, it will log the last returned result.
Your Code output is okay
const numbers = [1,2,3,4,5];
const doubleNumbers = [];
for (let i = 0; i < numbers.length; i+=1) {
doubleNumbers.push(numbers[i] * 2)
}
console.log(doubleNumbers)
Maybe You console the length of array
Maybe you aren't giving the entire context here?
What is numbers2 anyway? You declare a new array, doubleNumbers, but don't use it?
doubleNumbers.push(numbers[i] * 2)
should work just fine I believe.

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

access property in node.js [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
sorted = Object.keys(PLAYER_LIST).sort(function(a,b){return a.score - b.score}); // have key value
console.log(PLAYER_LIST[sorted[0]].team); // result:"A"
for(var loop=0; loop<=sorted.length; loop++) {
if(PLAYER_LIST[sorted[loop]].team == "A") { // error
some code...
}
}
When I sorting like this. console.log working well. But if sentence is not working. I receive error message. I don't know why. please help me.
if(PLAYER_LIST[sorted[loop]].team == "A") {
^
TypeError: Cannot set property 'team' of undefined
Your loop goes one step too far
for (var loop = 0; loop <= sorted.length; loop++) {
// ^^ here
An arrays length starts at zero when it's empty, and is 1 if the array contains one item.
If you have an array
var array = ['a']
arrays are zero based, so the first and only item is array[0], and the length is 1
When you iterate and you go all the way to the arrays length, you go one index too much, and you end up trying to get array[1], which doesn't exist.
What you wanted was
for (var loop = 0; loop < sorted.length; loop++) {...

splice does not remove element from array [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
Edit
Well, this is indeed embarrassing. Thank you all for noticing the typo, I would have deleted this question, but I can't (because it has answers). Let this be a monument.
I'm trying to write an app which, given an object and an array, removes the object from the array (if it exists), or adds it to the array (if it does not exist).
Initial array:
var permissions = [{
id: 3,
name: "Perm3"
}, {
id: 1,
name: "Perm1"
}];
Add\remove function:
triggerPermission = function(perm) {
var idx = permissions.indexOfById(perm);
if (idx === -1) {
permissions.push(perm);
} else {
permissions.slice(idx, 1); //should have been SPLICE...
}
};
helper function:
Array.prototype.indexOfById = function(obj) {
var idx = -1;
for (var i = 0; i < this.length; i++) {
if (this[i].id === obj.id) {
idx = i;
break;
}
}
return idx;
};
As can be seen on the plunkr, I'm trying to use this in an AngularJS app, with checkboxes as triggers. Some permissions are getting returned by splice (but the permissions array is not being changed), and some are not even getting returned. What am I missing here?
Your code uses slice, not splice.
slice does not modify the array, it returns a modified copy.
splice is the method you are after, which modifies the array in-place.
Exactly what meagar said. Slice will take a part of the array but leave the array untouched. Splice will actually "splice" something off.

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

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 = []**

Categories

Resources