How can I push a null value into the start of an array? - javascript

I have this code that fetches data and puts it into an array:
this.$httpGetTest(this.test.testId)
.success(function (data: ITestQuestion[]) {
self.test.qs = data;
});
It works and populates the array starting with self.test.qs[0].
However many times my code references this array (which contains a list of questions 1...x)
I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:
self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.
Ideally I would like to do this by putting something after the self.test.qs = and before data.

Push values at start of array via unshift
self.test.qs.unshift(null);

You need to use Splice(), It works like:
The splice() method changes the content of an array, adding new elements while removing old elements.
so try:
self.test.qs.splice(0, 0, null);
Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.
Here is demo:
var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";
alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());

You can start off with an array with a null value in it, then concat the questions array to it.
var arr = [null];
arr = arr.concat(data);

You could do something like:
x = [null].concat([1, 2, 3]);
Though there isn't anything wrong with doing something like:
x[index-1]
I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

Related

JS: Iterate over an array of objects to update object

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);

How to remove an element from array in javascript without making a new?

I read many answers but I didn't understand how to use splice in this case..
Suppose i have an array named alphabets like - ["a","b","c","d","e"] and i have to remove c from it. I dont want to create another array with c removed instead i want to update the same list each time an item is removed just like remove method in python. I know the index also so it can be like alphabets.remove[3]...to remove c. Please help me i am beginner.
Actually it would be better if there's a way that i can remove using just index number cause the names in array are very tough. Any help is appreciated
To modify the array rather than creating a new one, as you said you'd want the splice method. You pass the index of the item to remove, and the number of items to remove at that index:
const index = theArray.indexOf("c");
theArray.splice(index, 1);
Live Example:
const theArray = ["a","b","c","d","e"];
const rememberArray = theArray; // Just so we can prove it's the same array later
const index = theArray.indexOf("c");
theArray.splice(index, 1);
console.log(theArray);
console.log("Same array? " + (rememberArray === theArray));

Organise array push order

I've got an array. I push items multiple times into this array using a function. Below is an simplified version of the code.
var arr = [];
function pushItems(i){
//do something with i
var abc = "string"
arr.push(abc);
//do something with i
var xyz = "string"
arr.push(xyz);
}
Sometimes abc value is pushed before xyz. Sometimes xyz gets pushed before abc value. My question is how do I always have the abc value ahead of 'xyz' value?
So basically I need the array values to be [abc1, xyz1, abc2, xyz2, abc3, xyz3, ...] so on. How do I order the push accordingly?
This is wrong. According to the specification of this method:
The push() method adds one or more elements to the end of an array and
returns the new length of the array.
Please have a look here.
For a more formal approach please see the ECMAScript specification here.
The arguments are appended to the end of the array, in the order in
which they appear. The new length of the array is returned as the
result of the call.
Update
But even if the elements are added at the end of the array, I'm
looking a way of ordering my array.
You can use the sort function for this reason passing to it an appropriate function that will do the compare. For instance, let we have the following array
var array = [4,1,2,5,3];
and we want to order it in a descending order, we could do this like below:
var array = array.sort(function(a,b){ return b-a; });
Since you need your base64-strings to be in an arbitrary order in the array, sort them by an identifier you define.
var firstObj = {id: 0, base64: 'asdf'}
var secondObj = {id: 1, base64: 'qwer'}
var arr = []
// do stuff
// callback needs to have something along these lines:
function base64isLoaded(obj){
arr[obj.id] = obj.base64;
}
Now the 'front' image (as you gave this as example) can be given id: 0, so it ends up in the '0' spot of the array. I can't really help more without more information about how your code is structured.
EDIT: From your comment ("passing multiple items into pushItems"), I am going to assume that i (the argument) is an array and you iterate this array to transform each element into a base64 encoded string. You then want these encoded strings added to arr in the same order, correct?
easily done, simply make i an array of objects:
var i = [{source: 'abc'}, {source: 'xyz'}];
pushItems(i){
for(var c = 0; c < i.length; c++){
makeIntoBase64(i[c]);
}
}
makeIntoBase64(obj){
// this is whatever function that transforms it and takes a callback when it is done
transform(obj.source, function(result){ //pass the source to be encoded
//result should be base64 encoded string
obj.encoded = result;
});
}
after all this, the array i has objects with both .source and .encoded. If you need to know when ALL encoding is done, create a counter and add one to it in the transform callback, and check if counter === i.length every time. When it is, you know you have loaded all base64 strings and can run another function, adding these images to your catalogue or whatever else you need this for :)

How does this snippet for removing duplicates from an array work

Regarding this post (Remove Duplicates from JavaScript Array) on creating a new array of unique values from another array.
Code in question:
uniqueArray = myArray.filter(function(elem, pos) {
return myArray.indexOf(elem) == pos;
})
Using this as the test data:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
Desired result is an array with only unique values:
var unique_names = ["Mike","Matt","Nancy","Adam","Jenny","Carl"];
Where I'm at:
I understand that filter will run a function on each member of the array, and that elem is the element being reviewed, and that pos is its index. If something causes that function to return false, then that element will not be included in the new array. So walking through it, this happens:
Is myArray.indexOf("Mike") the same as 0? Yes, so add "Mike" to the new array.
Is myArray.indexOf("Matt") the same as 1? Yes, so add "Matt" to the new array.
Is myArray.indexOf("Nancy") the same as 2? Yes, so add "Nancy" to the new array.
[repeat for all elements. All pass.]
Basically I don't get why the 2nd Nancy would evaluate to false.
The indexof is the index of the first appearance of the element, so the second Nancy would get the index of the first Nancy, and would be filtered out.
6) Is myArray.indexOf("Nancy") the same as 5? No (it's 2, just like it step 3), so skip the duplicated "Nancy".
indexOf gives you the first occurrence of the item.

Remove element from array, using slice

I am trying to remove a element from my array using slice, but i can't get it to work, look at this piece of code.
console.log(this.activeEffects); // Prints my array
console.log(this.activeEffects.slice(0,1)); // Remove from index 0, and remove one.
console.log(this.activeEffects); // Prints array again, this time my element should be gone
Result of this is.
So what is get from this is, at first the array is whole, as it should be. Then its prints what is sliced of the array. Finally the third should be empty? or?
function removeItemWithSlice(index) {
return [...items.slice(0, index), ...items.slice(index + 1)]
}
Slice will create a new array. We create two arrays: from beggining to index and from index+1 to end. Then we apply the spread operator (...) to take the items of those arrays and create a new single array containing all the items we care. I will paste an equivalent way if you don't like the one liner:
function removeItemWithSlice(index) {
const firstArr = items.slice(0, index);
const secondArr = items.slice(index + 1);
return [...firstArr , ...secondArr]
}
I believe you're looking for splice. From W3 Schools:
The splice() method adds/removes items to/from an array, and returns the removed item(s).
Take a look at the example on that page; the use case there is similar to what you want to achieve.
EDIT: Alternative link to MDN, as suggested by Nicosunshine; much more information about the command there.
a.slice(0, index).concat(a.slice(index + 1))
.slice does not mutate the array, you could use .splice() to remove the item at index i in the array:
this.activeEffects.splice(i, 1)
This is what I was able to come up with :
var newArray = oldArray.slice(indexOfElementToRemove+1).concat(oldArray.slice(0,indexOfElementToRemove));
Array.prototype.slice()...
does not alter the original array, but returns a new "one level
deep" copy that contains copies of the elements sliced from the
original array. Elements of the original array are copied into the new
array as follows:
Whereas Array.prototype.splice()...
Changes the content of an array, adding new elements while removing old elements.
This example should illustrate the difference.
// sample array
var list = ["a","b","c","d"];
// slice returns a new array
console.log("copied items: %o", list.slice(2));
// but leaves list itself unchanged
console.log("list: %o", list);
// splice modifies the array and returns a list of the removed items
console.log("removed items: %o", list.splice(2));
// list has changed
console.log("list: %o", list);
Look at here :
http://www.w3schools.com/jsref/jsref_slice_array.asp
You can see that the slice method select object et throw them into a new array object ^^ So you can't delete an object like this, may be you can try a thing like this :
var a = ["a","b","c"]; (pseudo code)
/* I wan't to remove the "b" object */
var result = a.slice(0,1)+a.slice(2,1); /* If you considers that "+" is a concatenation operator, i don't remember if it is true... */

Categories