Check whether data present in array before .push - javascript

I am trying to add data to localStorage, it's a multi-dimensional array.
In order to "append" data to the array, I'm pulling it from localStorage with .getItem, using array.push to add my new data, and then resetting it with .setItem
The array data looks a little like this:
var wishlist = [
["210 Derby Road","http://localhost:8888/properties/210-derby-grove/"]
]
This works fine my only problem is not adding the data twice, so I need to search the array and see if it's present.
I tried first simply using the jQuery utility function:
console.log($.inArray(name, wishlist));
name in this case is 210 Derby Road so it should return true. This returned -1 even when the data was present.
I figured maybe because this is a multi-dimensional array that I needed to loop through the sub-arrays instead, so I created a for loop:
for (var i = 0; i < wishlist.length; i++) {
console.log($.inArray(name, i));
}
I'm still getting -1 returned.
How can I check my array wishlist to see if name is present?
JSFiddle

You almost got it right! Use:
for (var i = 0; i < wishlist.length; i++) {
console.log($.inArray(name, wishlist[i]));
}
cause wishlist[i] is the current Array.
Than to get a boolean do like:
if($.inArray(name, wishlist[i]) > -1) { /* do something*/ }

You can do with pure JS method Array.prototype.includes().
wishlist.findIndex(f => f.includes(name)) === -1 && // push it.

Related

updating a JSON objects value with a for loop in Java Script

I have an array of 11 objects which contain JSON data. I wrote a function in which a new key with a zero value is added to each of the objects. Now I want to update the value of the said key in all 11 objects. The data is stored in an array2 with 11 numbers. My for loop doesn't seem to work for this, and the only way to do it (so far) is to hard code it. Does anyone has a suggestion how this can be done?
The desired outcome would be this:
array[0].new_key = array2[0];
array[1].new_key = array2[1];
The first art of the function, before the for loop with j, is for adding the new key into the original array and that part works.
for (i = 0; i < array.length; i++) {
array.map(i => i.new_key = 0);
console.log(array)
for (j = 0; j < array2.length; j++) {
array[i].new_key = array2[j];
console.log(array)
}
}
}```
I split it into two functions, I realized that I made it too complicated and it didn't made sense. I wrote a second function that only updates all the key values, so indeed, I removed the inner loop as it was not needed. Thank you for the help.
.map() does not modify the original array:
The map() method creates a new array with the results of calling a
provided function on every element in the calling array.
You will want to get the result of the map by assigning it to a variable, and see what is happening there. Right now you don't do anything with it, so it will just disappear.
While the above is true for maps, in this case the original array is being modified as we access the object's properties and modify them there.

Deleting items from array within for loop

I'm facing a javascript problem with deleting items in an array within a for loop.
My code is checking the existence of a localStorage item containing a stringified object, parse it, run the for loop, do some stuff (that works great) on each item, delete the item if conditions are good, and finally save the new array to the localStorage item.
Here it is :
if (localStorage.getItem(user_id+"_tosave") && localStorage.getItem(user_id+"_tosave").length>1){
var local_tosave = JSON.parse(localStorage.getItem(user_id+"_tosave"));
if (local_tosave.length>0){
for (i = 0; i < local_tosave.length; i++) {
// SOME OTHER STUFF HERE...
if (navigator.onLine){local_tosave.splice(i,1);}
};
localStorage.setItem(user_id+"_tosave",JSON.stringify(local_tosave));
alert(localStorage.getItem(user_id+"_tosave")); // DISPLAY TO CHECK
}
}
Only the last item of the array is deleted... why is that ? The splice function breaks the loop when there's more than one element in the array.
I guess there's something about object & iteration as i saw in other conversations but the solutions given didn't work for me.
Fyi, i tried local_tosave.splice(i--,1); which was even worse.
Thanks for your help.
I would try to walk array backwards, if order doesn't matter. Like this
for (i=local_tosave.length-1; i>=0; i--) {
so the elements on the end would be chopped off and the rest of array would be untouched.
hope it helps
The problem is in the increment. I suggest to use an other loop with while.
var i = 0;
while (i < local_tosave.length) {
if (navigator.onLine) {
local_tosave.splice(i, 1);
continue; // because i should stay
}
i++;
};

for..in loop loops over non-numeric indexes “clean” and “remove”

This is something very basic I might be missing here but I haven't seen such result till now.
I have a for loop where options.headers.length is 3. And in for loop I am dynamically creating a table header. Ideally this loop should run three times for 0 1 and 2 but when I have printed index it's printing 0,1,2,clean and remove. I haven't seen clean and remove as indexes. I know this information is not sufficient enough but if you have any clue please suggest. something might be overriding this is all I am concluded too after my debugging.
for (index in options.headers)
if you don't want to iterate clean and remove then change the loop to:
for (var i=0; i< options.headers.length;i++){
//use i for getting the array data
}
if you use for (index in options.headers) it will iterate for non-numeric keys also.
don use just index (as that is = window.index = global = bad) use var index
(read more here https://www.google.pl/webhp?sourceid=chrome-instant&ion=1&espv=2&ie=UTF-8#q=globals+javascript+bad)
you have to check does the array has it as own property or maybe its some function (more after answer)
for (var index in options.headers) {
if (options.headers.hasOwnProperty(index) {
// code here
}
}
more about #2:
let's say we have
var array = [0,1,2,3];
and besides that, extending array with function (arrays can have functions in javascript and strings too)
Array.prototype.sayHello = function() {
alert('Hello');
};
then your loop would print sayHello as part of the array, but that's not it's own property, only the arrays
I assume that options.headers is an Array?
This happens when you (or some framework you load) adds methods to the Array prototype. The "for in" loop will enumerate also these added methods. Hence you should do the loop for an array with:
for (var i = 0; i < options.headers.length; i++)
That way you will only get the real values instead of added methods.

AngularJs pushing multiple values from array to another with databinding refreshing

I am getting an array from the server which can contain 0..n elements in an array. I then add that to array I use locally for databinding (basically cache data in client). When doing it this way databiding works without any problems:
for (var i = 0 ; i < data.Result.length ; i++) {
scope.cachedData.push(data.Result[i]);
}
Meaning - view refreshes, everything works. But when I try: scope.cachedData.concat(data.Result); it won't work. Why is that?
If you want to push everything in a single instruction use apply without breaking the reference to scope.cachedData
Array.prototype.push.apply(scope.cachedData, data.Result);
Also, I know this is a little bit off topic but if you want to insert at a specific index you can use splice with apply
// I definitely want to prepend to my array here
var insertionIndex = 0,
// we don't want to delete any elements here from insertionIndex
deleteCount = 0;
// Because we use apply the second argument is an array
// and because splice signature is (startIndex, noOfElementsToDelete, elementsToInsert)
// we need to build it
Array.prototype.splice.apply(scope.cachedData, [insertionIndex, deleteCount].concat(data.Result));
Imagine your array scope.cachedData = [3,4]; and data.Result = [1,2];, with the code above scope.cachedData will become [1,2,3,4].

json jquery filter javascript array

I have a json object array. I want to search the array and for each object, create a list of 'services' that is a comma-seperated list of all the keys which have a value of "yes".
The list of json objects with the services list is then displayed in html using jquery's each.
Its a large json file so I want to do it as efficiently as possible.
I already have the object's properties being accessed through jQuery's each (ie, obj.name)
-- so I think it should be possible to filter the services listed for each object using
jQuery's filter, and then display the key if the value is yes.
But it seems like a more efficient option would probably be to create a new javascript array, join the services with a value of yes and then add that variable to the html being
appended.
Im not sure which would be faster and so far havent been very successful at either... so any advice and examples would be very helpful.
Here's what the json array looks like:
[
{"name":"name1",
"service1":"y",
"service2":"y",
"service3":"n",
},
{"name":"name2",
"service1":"n",
"service2":"y",
"service3":"n",
},
];
If you just want to filter the array then use grep.
grep - Finds the elements of an array which satisfy a filter function. The original array is not affected.
http://api.jquery.com/jQuery.grep/
First off, delete trailing commas. Internet Explorer gets really, really confused by them. Anyway, I assume you don't want to "search" the array when you say "for each value"; you want to iterate through the array and parse it into a more usable list. The first method I'd suggest is just passing what you want as the array you desire, but if that's not an option, what you're looking for is some variant of this, which should be fairly efficient (jsFiddle example):
var json = [
{"name":"name1", "service1":"y", "service2":"y", "service3":"n"},
{"name":"name2", "service1":"n", "service2":"y", "service3":"n"}
];
var parsed = {};
for (var i = 0, iLen = json.length; i < iLen; i++) {
// Assuming all we need are the name and a list
var name;
var list = [];
for (var key in json[i]) {
var value = json[i][key];
// We need to hold on to the name or any services with value "y"
if (key === "name") {
name = value;
} else if (value === "y") {
list.push(key);
}
}
// Add them to the parsed array however you'd like
// I'm assuming you want to just list them in plain text
parsed[name] = list.join(", ");
}
// List them on the web page
for (var key in parsed) {
document.write(key + ": " + parsed[key] + "<br>");
}
That way you wind up with a display to the visitor of the services available and still keep an array around for further use if necessary.
jQuery.inArray() Search for a specified value within an array and return its index (or -1 if not found).
http://api.jquery.com/jQuery.inArray/
Or
http://api.jquery.com/jQuery.each/

Categories

Resources