I have an Array of a few hundred JSON Objects...
var self.collection = [Object, Object, Object, Object, Object, Object…]
Each one looks like this...
0: Object
id: "25093712"
name: "John Haberstich"
I'm iterating through the Array searching each Array.id to see if it matches any ids in a second Array...
var fbContactIDs = ["1072980313", "2502342", "2509374", "2524864", "2531941"]
$.each(self.collection, function(index, k) {
if (fbContactIDs.indexOf(k.id) > -1) {
self.collection.splice(index, 1);
};
});
However this code only works to splice three of the Objects from the self.collection array and then it breaks and gives the following error:
Uncaught TypeError: Cannot read property 'id' of undefined
The line that is causing the error is this one...
if (fbContactIDs.indexOf(k.id) > -1) {
Could anyone tell me what I'm dong wrong here?
Because the length of collection will change, the trick is to loop from rear to front
for (var index = self.collection.length - 1; index >= 0; index--) {
k = self.collection[index];
if (fbContactIDs.indexOf(k.id) > -1) {
self.collection.splice(index, 1);
};
}
You should not change the length of an array while iterating over it.
What you're trying to do is filtering and there's a specific function for that. For example:
[1,2,3,4,5,6,7,8,9,10].filter(function(x){ return (x&1) == 0; })
will return only even numbers.
In your case the solution could then simply be:
self.collection = self.collection.filter(function(k){
return fbContactIDs.indexOf(k.id) > -1;
});
or, if others are keeping a reference to self.collection and you need to mutate it inplace:
self.collection.splice(0, self.collection.length,
self.collection.filter(function(k){
return fbContactIDs.indexOf(k.id) > -1;
}));
If for some reason you like to process elements one at a time instead of using filter and you need to do this inplace a simple approach is the read-write one:
var wp = 0; // Write ptr
for (var rp=0; rp<L.length; rp++) {
if (... i want to keep L[x] ...) {
L[wp++] = L[rp];
}
}
L.splice(wp);
removing elements from an array one at a time is an O(n**2) operation (because for each element you remove also all the following ones must be slided down a place), the read-write approach is instead O(n).
Related
Good evening, I attempting to detect duplicate characters in a string. More specifically, I am trying to find up to two different duplicates within an Array. If there is one duplicate, add a sub-string, and if there is another duplicate, add a different sub-string. Is there any way to do this?
Here is some example code I have so far:
var CodeFieldArray = ["Z80.0", "Z80.1", "Z80.0", "Z70.4"];
/* We have an array here used to create the final string at the end of the
code. It is a dummy array with similar variables in my actual code. For
reference sake, there may be only one object in the array, or 7 total,
depending on the user's input, which is where the duplicate detection should
come in, in case the user enters in multiples of the same code. */
var i, Index;
for (i = 0, L = 0; i < CodeFieldArray.length; i++) {
Index = CodeFieldArray[i].indexOf(CodeFieldArray[i]);
if(Index > -1) L += 1;
Extra0 = CodeFieldArray.indexOf("Z80.8");
Extra1 = CodeFieldArray.indexOf("Z80.9");
if(L >= 2 && Extra0 == -1) CodeFieldArray.push("Z80.8");
Extra0 = CodeFieldArray.indexOf("Z80.8");
if(L >= 4 && Extra0 != -1 && Extra1 == -1) CodeFieldArray.push("Z80.9");
console.println(Extra0);
}
/*^ we attempted to create arguments where if there are duplicates
'detected', it will push, "Z80.8" or, "Z80.9" to the end of the Array. They
get added, but only when there are enough objects in the Array... it is not
actually detecting for duplicates within the Array itself^*/
function UniqueCode(value, index, self) {
return self.indexOf(value) === index;
}
CodeFieldArray = CodeFieldArray.filter(UniqueCode);
FamilyCodes.value = CodeFieldArray.join(", ");
/* this is where we turn the Array into a string, separated by commas. The expected output would be "Z80.0, Z80.1, Z70.4, Z80.8"*/
I have it to where it will add "Z80.8" or "z80.9" if they are not present, but they are being added, only if there are enough objects in the Array. My for-loop isn't detecting specifically the duplicates themselves. If there was a way to detect specifically the duplicates, and create an argument based off of that, then we would be doing grand. The expected output would be "Z80.0, Z80.1, Z70.4, Z80.8"
You can use Set and forEach and includes
var CodeFieldArray = ["Z80.0", "Z80.1", "Z80.0", "Z70.4"];
let unique = [...new Set(CodeFieldArray)];
let match = ['Z80.8','Z80.9'];
let numOfDup = CodeFieldArray.length - unique.length;
if(numOfDup){
match.forEach(e=>{
if(!unique.includes(e) && numOfDup){
unique.push(e);
numOfDup--;
}
})
}
console.log(unique.join(','))
So the idea is
Use Set to get unique values.
Now see the difference between length of original array and Set to get number of duplicates.
Now will loop through match array and each time we push item from match array into unique we reduce numOfDup by so ( to handle case where we have only one duplicate or no duplicate ).
In the end join by ,
You could do something like this:
var uniqueArray = function(arrArg) {
return arrArg.filter(function(elem, pos,arr) {
return arr.indexOf(elem) == pos;
});
};
uniqueArray ( CodeFieldArray )
In this code I want to remove an element from the cart_products array.
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
$.each(cart_products,function(key, item) {
if(item.indexOf(product+"^") !== -1){
cart_products.splice(key, 1);
}
});
But I get this error in Google Chrome console:
Uncaught TypeError: Cannot read property 'indexOf' of undefined
Is there something wrong with the code?
Thanks for your help.
The problem is that you're modifying the array while jQuery's $.each is looping over it, so by the time it gets to the end, the entry that used to be at index 2 is no longer there. (I admit I'm a bit surprised $.each behaves that way, but I haven't used $.each in at least five years, so...)
If the goal is to remove matches from the array, the better choice is filter:
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
cart_products = cart_products.filter(function(item) {
return item.indexOf(product+"^") === -1;
});
console.log(cart_products);
...or alternately if it's important to modify the array in-place rather than creating a new one use a boring for loop as Andreas points out looping backward through the array so it doesn't matter when you remove things:
var cart_products = ["17^1", "19^1", "18^1"];
var product = 17;
var target = product + "^";
for (var index = cart_products.length - 1; index >= 0; --index) {
if (cart_products[index].indexOf(target) !== -1) {
cart_products.splice(index, 1);
}
}
console.log(cart_products);
First of all, you don't need to use a jQuery each for this. Second, it's not a great idea to alter an array that you are operating on. If you're trying to remove elements from an array, use filter. Filter has the following signature:
someArray.filter(function(item, index, array) {
// return a value that is truthy to keep an item or falsey to remove it
})
Filter returns a new array with only the values that match what you want. That means you don't mess with your original array, which is a good idea anyways. In your case it would look like this:
var filteredProducst = cart_products.filter(function(item) {
return item.indexOf(product + "^")
})
I tried to find out some good examples but SO seems to have mainly examples from 4-5 years ago and I would like to use a solution that would work using modern browser capabilities.
Ihave an array of test objects:
var tests;
Each test object contains a testId.
How can I remove test object with testId = 25 from the array tests. I was thinking of a for loop but is there a cleaner way to do this?
The best answer depends on whether you know in advance whether there's at most one match, or potentially more than one (and in the latter case whether you want to remove all of them or just the first)
Removing all matches
The "simplest" way is to use filter, although strictly that produces a new array without the matching element:
tests = tests.filter(function(e) {
return e.testId !== 25;
});
This is OK, unless other code is holding a reference to the original array.
Modifying the array safely "in-place" still appears to require a combination of a for loop with .splice:
for (var i = 0; i < tests.length; ) { // nb: deliberate .length test
if (tests[i].testId === 25) {
tests.splice(i, 1);
} else {
++i;
}
}
The "safely" caveat is because the functional methods of iterating through an entire array will get confused if the current element in the array is removed. That is not a concern in the "first match" methods shown below.
Removing first (or only) match
The plain for method is still pretty simple (and probably most efficient, too!)
for (var i = 0, n = tests.length; i < n; ++i) {
if (tests[i].testId === 25) {
tests.splice(i, 1);
break;
}
}
The .some method per Johan's answer can iterate through an array and then exit on first match (although some may object on philosophical grounds to a boolean predicate function also mutating the array):
var didRemove = tests.some(function(e, i, a) {
if (e.testId === 25) {
a.splice(i, 1);
return true; // causes the loop to exit
}
});
In ES6-draft there's .findIndex, which is a generalisation of .indexOf:
var index = tests.findIndex(function(e) {
return e.testId === 25;
});
if (index >= 0) {
tests.splice(index, 1);
}
One way is to loop through all objects and splice a matching object out of the array.
Instead of forEach I use some (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some). Because with the some method you can "break" the loop by returning true so that you don't need to go through all objects if a match has been found.
tests.some(function(testObject, index) {
if (testObject.testId === 25) {
tests.splice(index, 1);
return true;
}
});
Or wrap it in a function
var removeObjectById = function(id) {
tests.some(function(testObject, index) {
if (testObject.testId === id) {
tests.splice(index, 1);
return true;
}
});
}
removeObjectById(25)
I have an array:
var productIds = new Array("1","6","7","Product-Total","ccFirst","ccLast","email","ccExpMonth","ccExpYear","billingAddress","billingCity","billingState","billingZip");
I want to delete a value if it is not a number:
for(var i=0; i<productIds.length; i++){
if(isNaN(Number(productIds[i]))) {
productIds.splice(i,1);
}
}
It seems the splice method is affecting the positions of the values.
I found this solution(Looping through array and removing items, without breaking for loop) which is what I think I need, but I can't figure out how to implement their answers for my code.
How can I fix my problem?
btw, I posted a more detailed jsFiddle: http://jsfiddle.net/fte3m/2/
When you delete the entry at index i, you need to subtract 1 from i so the entry that was moved down is not skipped.
for(var i=0; i<productIds.length; i++){
if(isNaN(productIds[i])) {
productIds.splice(i--,1); // <-- Decrement i
}
}
As RobG points out in his comment, it's easier to simply process the array in the other direction:
for(var i=productIds.length - 1; i>=0; i--){
if(isNaN(productIds[i])) {
productIds.splice(i,1);
}
}
Alternatively, if you don't mind reassigning productIds to be a new array object and you are running JS 1.6 or later:
productIds = productIds.filter(function (id) {
return !isNaN(id);
});
(Note that in the above, I just use isNaN(value) rather than isNaN(Number(value)). Whenever Number(value) would return NaN, isNaN(value) will return true, and vice versa. Note also that neither approach will filter out a null id, since Number(null)==0 and isNaN(null)==false. If you want to exclude null entries from the result, you will need to test for that separately.)
How can I call a JavaScript function if a string contains any of the items in an array?
Yes, I can use jQuery :)
You could use the grep function to find if there are any elements that satisfy the condition:
// get all elements that satisfy the condition
var elements = $.grep(someArray, function(el, index) {
// This assumes that you have an array of strings
// Test if someString contains the current element of the array
return someString.indexOf(el) > -1;
});
if (elements.length > 0) {
callSomeFunction();
}
You could use some(), a Mozilla extension which has been added to ECMAScript 5:
var haystack = 'I like eggs!';
if(['spam', 'eggs'].some(function(needle) {
return haystack.indexOf(needle) >= 0;
})) alert('spam or eggs');
Simply loop over the items in the array and look for the value. That's what you have to do anyway even if you use some method to do it for you. By looping yourself you can easily break out of the loop as soon as you find a match, that will by average cut the number of items you need to check in half.
for (var i=0; i<theArray.length; i++) {
if (theArray[i] == theString) {
theFunction();
break;
}
}