JavaScript Array undefined element [duplicate] - javascript

This question already has answers here:
How can I add new array elements at the beginning of an array in JavaScript?
(12 answers)
Closed 6 years ago.
I´ve got a function which should add an element at the start of an array.
But I always get an undefined element at the end of my array. I hope someone can help me :)
function putToFirst(e){
var array = [];
array.push(e);
this.arrayList = array.concat(this.arrayList);
}
EDIT:
class List {
constructor () {
super()
this.arrayList = [];
}
putToFirst(e) {
this.ArrayList.unshift(e);
}
}
thats the class. I create a new object from the class list and call the function putToFirst on this object. But I always get an Array with 'undefinded' in the end

this.arraylist is wrong this represent a current object you are not currently using any class in above code you just need to change
function putToFirst(e){
var array = [];
var arrayList=[];
array.push(e);
arrayList = array.concat(arrayList);
console.log(arrayList);
}

Related

filter an HTML-elements filled array (javascript) [duplicate]

This question already has answers here:
How to filter an array from all elements of another array
(24 answers)
Closed 2 years ago.
i have two arrays that both contains HTML Elements, i want to remove from the first array all the elements that are also present in the second one.
var a = [document.createElement('div'), document.createElement('span')],
b = [document.createElement('span'), document.createElement('p')];
filter(a,b) == [document.createElement('span')] // true
i tried with something like this, but it seems like it doesn't work:
var filter = function(a,b) {
return a.filter(element => {
return b.map(element_ => {
return element.isEqualNode(element_);
}).includes(false);
});
}
let res = a.filter((el)=> { return b.find((el2)=> el.localName === el2.localName)});
// res = [span];
So, el.localName is a property of a HTML element of type string which contains the name of the element. Which can be used for comparing two HTML elements
For Example: In Case of div its 'div'
Code returns the common element present in both the arrays.

Javascript Grammer: how to assign correct values to an array of objects [duplicate]

This question already has answers here:
new Array(_).fill(object) does not create new instances of object [duplicate]
(5 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Closed 2 years ago.
let's look at the code:
Test() {
let array1 = new Array(5).fill({ a: 0 })
let array2 = new Array(5).fill({ a: 0 })
for (let i = 0; i < 5; i++) {
setTimeout(() => {
array1[i].a = i
array2[i] = {a:i}
console.warn("array = ", array1)
console.warn("array2 = ", array2)
}, 0.2 * i)
}
}
In this case, I wanna assign a series of values to the array1 & array2, and there are two ways to do it, which lead to totally different results.
In the case array1[i].a = i, after all the code is ran, the result is array = [{a:4},{a:4},{a:4},{a:4},{a:4}], which is not what i wanted.
In the second case array2[i] = {a:i}, the result will be [{a:0},{a:1},{a:2},{a:3},{a:4}] as expected.
I wanna know why is it like this? What's the machanics behind this phenomenon?
Thank you.
When you call .fill() and pass an object, you assign the exact same object to every element of the array. Thus, modifying a property at one array index modifies the same property at all the other indexes, because they're all pointing to the same thing.
There are a variety of ways around this issue. You could fill the array with 0 or null or some dummy value and then iterate through with .forEach(), or more simply just use an indexed for loop to initialize each element. If you initialize with { a: 0} in a for loop, a new object will be created on each iteration.

JavaScript matrix wired behaviour when using new Array() [duplicate]

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.

How to remove duplicated objects from an Array in javascript [duplicate]

This question already has answers here:
Remove duplicate values from JS array [duplicate]
(54 answers)
Closed 6 years ago.
I am using above code and removing the items based on id
I am getting id is not defined while comparing i+1 item when i reaches to maximum array length.
Appreciate your help....
var arr = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":474.5,"top":16},{"id":"0-block-2","left":686.5,"top":0}];
Expecting outout = [{"id":"0-block-0","left":206.5,"top":0},{"id":"0-block-1","left":446.5,"top":0},{"id":"0-block-2","left":686.5,"top":0}]
Array.prototype.unique = function(){
var passNum = this.length;
var _self = this;
// to repeat loops n*n times
while(passNum>0){
for(var i = 0;i<this.length;i++) {
if(this[i].id==this[i+1].id){
var _indx = this.indexOf(this[i]);
this.splice(_indx,1);
}
}
passNum = passNum-1;
}
return this;
};
You can do this with ES2015 Sets.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Set
EDIT: If you can't use ES2015, there is a polyfill available.

Sort an array in Javascript/JQuery [duplicate]

This question already has answers here:
How to sort an array of objects with jquery or javascript [duplicate]
(6 answers)
Closed 8 years ago.
There is an array emails having few attributes To, From, Subject, Description. I retrieve records from database and populate all rows in this array. I use to access all rows as follows:
for (var i = 0; i < emails.length; i++) {
var To = emails[i].To;
var Sender = emails[i].Sender;
var Subject = emails[i].Subject;
var Description = emails[i].Description;
}
Now I need to sort this array alphabetically by To values and store the sorted emails in another array sortedemails. How can I do this in easiest possible way in Javascript/JQuery?
Thanks.
Arrays in javascript have a sort function.
emails.sort(function(a, b) {
if (a.To < b.To) {
return -1;
} else {
return 1;
}
}
JavaScript arrays have a built-in .sort method. No loops (or jQuery needed).
emails.sort(function(a, b){
return a.To.localeCompare(b.To);
});
This will modify the email array. If you want to save the original (unsorted) array, you'll need to copy the array before sorting.
var sortedemails = emails.slice(0);
sortedemails.sort(function(a, b){
return a.To.localeCompare(b.To);
});

Categories

Resources