splice does not remove element from array [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
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.

Related

Store values inside array jquery [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 3 years ago.
Improve this question
I have multiple inputs, for example:
<input id=xxx_1>
<input id=xxx_2>
I want the values from input to be stored inside an array. At the moment what I have is this but it doesn't work. I have tried to Google it and I can't find any solution. I can't understand why this does not work.
var array = [];
for (var i = 1; i >= 14; i++) {
array[i] = $(this).find("#xxx_" + i + "").val();
}
What I what is to have an array like this:
[ value, value, value,... ]
Thanks for the help
You could make use of attributs starts with selector to select all elements who id starts with xxx, then you can iterate over these elements using .each()
var array = [];
$( "[id^='xxx']" ).each(function() {
array.push(this.value);
});
console.log(array);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input id="xxx_1" value="123">
<input id="xxx_2" value="456">
Your comparison operator in your for loop is the wrong way round, and so your code never enters it.
You probably want to look for when i is less than or equal to 14, using <= .
var array = [];
for (var i = 1; i <= 14; i++) {
array[i] = $(this).find("#xxx_" + i + "").val();
}

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++) {...

Why does my function return undefined when trying to return the max number from an 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
My function returns undefined rather than 3, I'm aware I can use:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Math/max
However, I want to first try and see if I can do so without utilizing a native function since I'm trying to improve my skills as a dev.
var my_max = function(arr){
var max=arr[0];
for (var i = 0; i < arr.length; i++){
if (arr[i] > max) {
max=arr[i];
}
}
return max;
};
console.log(my_max(1, 2, 3));
There's no array there. You're just passing three numbers to the function. You should instead pass an array of three numbers:
console.log(my_max([1, 2, 3]));
Alternatively, you can use rest parameters in your function, like that:
var my_max = function(...arr){
// ...
}
Then you can call it without using an array:
console.log(my_max(1, 2, 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

Categories

Resources