This question already has answers here:
Array.push() if does not exist?
(30 answers)
Remove duplicates form an array
(17 answers)
Closed 4 years ago.
I have a simple array with a few elems & a new elem , trying to check the elems with a function , push the new elem into the array if not already present & ignore it if it is.
I created a function with an if /else statement but the code always adds the new item to the array.
var arr=['a','b'];
var newElem='c';
function f(){
for(var i=0; i<arr.length; i++){
if(arr[i] == newElem){ console.log('Exists');return }
else {arr.push(newElem);console.log(arr); return }
}
}
f();
The code works fine if the new item not present in the array but if it's ,the new elem still being pushed into the array?
Pls anyone could help , don't want to ask the teacher , it looks so simple ?
Check if element exists first like so:
const arr = ['a', 'b'];
const newElem = 'c';
if (arr.indexOf(newElem) === -1) {
arr.push(newElem);
}
Related
This question already has answers here:
How to update one Javascript object array without updating the other [duplicate]
(3 answers)
What is the most efficient way to deep clone an object in JavaScript?
(67 answers)
Closed 3 years ago.
I currently have an array of objects called posts.
for(var i = 0; i < posts.length; i++){
let post = posts[i]
let { item, category } = post
let postCollections = categories[category]
for(var col in userCollections[category]){
let items = userCollections[category][col].items
if(items && col){
postCollections[col]['item'] = item
console.log("HERE!, item)
if(item in items){
postCollections[col]['joined'] = true
}else{
postCollections[col]['joined'] = false
}
}
}
posts[i]['collections'] = postCollections
}
When this is run, the print out for "HERE!" shows the item value is unique. When I print out posts and look at the value for key items they all show the same item.
This was a tough solve. Turns out the line where I set postCollections was using the same object over and over again. Copying the object like this has done the trick:
let postCollections = JSON.parse(JSON.stringify(categories[category]));
This question already has answers here:
Array.fill(Array) creates copies by references not by value [duplicate]
(3 answers)
Closed 4 years ago.
When i use Array.fill to fill a multidimensional array, i get a weird behaviour when pushing to one of the arrays:
var arr = Array(2).fill([]);
arr[0].push(5);
console.log(arr);
//=> prints [[5], [5]]
fill is essentially doing this:
var content = [];
for (var i = 0; i < 2; i += 1) {
arr[i] = content;
}
So, your array will have a reference to the array you've passed to fill in each property.
It sounds weird, but what your code actually does is create an array ([]) and put a reference for that array in each of the items of the Array(2). So whenever you change that reference - every array that is referenced to that Array is changed.
It's exactly the same as:
var a = [];
var arr = Array(2).fill(a);
a.push(5);
console.log(arr[0][0], arr[1][0]);
a[0] = 2;
console.log(arr[0][0], arr[1][0]);
You can see that the values inside the arr are affected by the change to the a array.
This question already has answers here:
Javascript array length incorrect on array of objects
(3 answers)
Closed 8 years ago.
I don't understand why is array so strange when I add element by key.
For example:
var test = new Array();
test['a'] = 'aaa';
test['b'] = 'bbb';
test.length == 0; // true. Why?
And when I run:
test.map(function(el){
console.log(el);
});
// nothing print. Why?
When I add element with push method everything works OK. Thanks
Arrays in javascript are not associative, you can't set keys like that i.e.
var test = [];
test.push('aaa');
test.push('bbb');
// OR
test[0] = 'aaa';
test[1] = 'bbb';
test.length = 2
This question already has answers here:
Elements order in a "for (… in …)" loop
(10 answers)
Closed 8 years ago.
i need to get real order of simple javascript abject, but i get incorrect answer from this code:
var Obj={"x":"z", "2":"a", "1":"b"};
for(i in Obj)
document.write(Obj[i]+"<br>");
I expect to see z, a, b as answer, but i get b, a, z
See the code in action:
http://jsfiddle.net/gpP7m/
There's no guaranteed order in object keys iteration.
A for...in loop iterates over the properties of an object in an
arbitrary order
If you need one, use an array of key/value elements :
var obj=[
{key:"x", value:"z"},
{key:"2", value:"a"}
];
for (var i=0; i<obj.length; i++) document.write(obj[i].value+'<br>');
On a modern browser (not IE8), you can do :
document.write(obj.map(function(kv){ return kv.value }).join('<br>'));
(which doesn't do exactly the same but probably does what you want)
Check for below sample too
var data1 = {"x":"z", "2":"a", "1":"b"};
var arr = [];
var i=0;
$.each(data1,function(index,value) {
arr[i++] = value;
});
var len = arr.length-1;
while( len>=0 ) {
if( arr[len] !== undefined ) {
alert(arr[len]);
}
len--;
}
and referece link is Reverse object in jQuery.each
And fiddle update http://jsfiddle.net/gpP7m/3/
This question already has answers here:
Find object by id in an array of JavaScript objects
(36 answers)
Closed 8 years ago.
I have JSON objects that have several properties such as an id and name. I store them in a JavaScript array and then based on a dropdownlist I want to retrieve the object from the JavaScript array based on its id.
Suppose an object has id and name, how do I select them from my array variable?
var ObjectsList = data;
var id = $("#DropDownList > option:selected").attr("value");
ObjectsList["id=" + id];
Since you already have jQuery, you could use $.grep:
Finds the elements of an array which satisfy a filter function. The original array is not affected.
So something like this:
var matches = $.grep(ObjectsList, function(e) { return e.id == id });
that will leave you with an array of matching entries from ObjectsList in the array matches. The above assumes that ObjectsList has a structure like this:
[
{ id: ... },
{ id: ... },
...
]
If you know that there is only one match or if you only want the first then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id != wanted_id)
continue;
m = a[i];
break;
}
// m is now either null or the one you want
There are a lot of variations on the for loop approach and a lot of people will wag a finger at me because they think continue is a bad word; if you don't like continue then you could do it this way:
for(var i = 0, m = null; i < ObjectsList.length; ++i) {
if(ObjectsList[i].id == wanted_id) {
m = ObjectsList[i];
break;
}
}