Move element in array from certain index into 0 - javascript

I guess i do something stupid so forgive me, but both methods don't change anything .
I want to move element from certain index - into index 0 .
I have an array with 2 elements .
first way
console.log(index); //1
console.log(localProductPhotos);
localProductPhotos.unshift(localProductPhotos.splice(index, 1)[0]);
console.log(localProductPhotos);
array will stay/print the same order
second way
Array.prototype.move = function(from, to) {
this.splice(to, 0, this.splice(from, 1)[0]);
};
localProductPhotos.move(index,0); //index prints 1
both cases the array prints the same order.
EDIT:
This is the print:
log
EDIT:
The above works on a simple array of strings, but my array is array of blob files as you can see in the photo.
var localProductPhotos=[];
//...
localProductPhotos.push(file);

Based on your example/log, I can surmise that you want to move the element in your index to the first one. So you can just do this:
localProductPhotos.unshift(localProductPhotos[index]);

Related

How to filter every element except first in an array? JS

I have a 2D array which looks like this:
numbers = [[], [1,2,4], [], [1,2,6], []]; //Not always the same
Is it possible to use prototype.filter() to erase every empty array, except the first array in the index (numbers[0])? So far, haven't found an answer.
If not, should i use a for loop or there's another prototype function i'm not aware of?
This should do the trick
numbers.filter((subArray, index) => subArray.length > 0 || index === 0);
Why don't you filter for every array that is empty then add the first array back in afterward?
// Filter for only arrays with lengths greater than 0
myArray.filter(subArray=> subArray.length > 0);
// Add an empty array to the beginning of the array
myArray.unshift([]);

How does this line " return fileNameParts[fileNameParts.length-1]; " work?

function getFileExtension(i) {
if (i.indexOf(".") < 0) {
return false;
}
var filenameParts = i.split(".");
return filenameParts[filenameParts.length-1];
}
Here's the whole code. I understand it all except for the last line. I know what it does, but I don't know how or why. The second to last line splits the string at the ".", and then how does the last line actually get all the letters on the right side of the string?
By calling var filenameParts = i.split("."); an array is created containing the different parts. Imagine we use the filename test.txt and we use that string to split, we'll get an array like so:
filenameParts = ["test", "txt"]
Because the index of the first item in an array is 0, and we need the last item in the array, we call filenameParts.length-1 to get to the last item.
More information about javascript arrays can be found here.
The .split() function returns an array of strings, not a string. The expression filenameParts[filenameParts - 1] fetches the last element of the array.
filenameParts.length delivers the count of the filenameparts, split in the line above. filenameParts[number] delivers the one item of the array, which is positioned at number. -1 because arrays start at 0 not at 1. So it delivers the last item of the array. Clear?
filenameParts is an array and you read a single value with it's index. A value in this case is one part of the string between the ".".
filenameParts.length is equal to the count of values inside the array. As an array index starts with 0 you have to subtract 1 to get the index of the last value.
It looks like your function getFileExtension is designed to return the file extension of a given file. For example getFileExtension('image.gif') would return gif.
In the line (given that i is set to image.gif):
var filenameParts = i.split(".");
filenameParts will be an array, where image.gif has been split on the period. So filenameParts = ['image', 'gif'] where element zero is image and element one is gif. Remember that array indices are zero-based!
In the last line:
return filenameParts[filenameParts.length-1];
the function itself will return the last element in the filenameParts array (['image', 'gif']) which is gif. The part filenameParts.length-1 says get the length of the filenameParts array (which is 2), subtract 1 (which is 1), and return that element of the filenameParts array. So we return filenameParts[1] which is the last element of the array (remember, array indices are zero-based).
To get the last element of the array we could also have done
return filenameParts.pop();
because the pop() function returns the last element of an array.
var filenameParts = i.split('.') returns an array of made of the splitted elements of i
filenameParts[filenameParts.length-1];
select the last element of that array

How does splice work exactly in angularjs/javascript?

I have an array of objects:-
$scope.obj=[{"id":1,"content_type_name":"collections"},{"id":2,"content_type_name":"collections"},{"id":3,"content_type_name":"random"}];
Now when i try running my loop of angularForEach only the first collection entry(i.e. one with id=1 is getting removed but the one with id=2 stays). Ideally expected output should only be an object with id=3. Following is the code:-
angular.forEach($scope.obj, function(content, index){
if(content.content_type_name == "collections"){
$scope.obj.splice(index,1);
}
});
However when I run this, it works perfectly fine:-
for(var i=$scope.obj.length-1;i>=0;--i){
if($scope.obj[i].content_type_name == "collections"){
$scope.obj.splice(i,1);
}
}
I am not getting a clear picture of why splice is not working.
Some help please?
So the angular forEach loop starts at the beginning of the array, while your second example with the for loop starts at the end and goes back through. Since you're removing an element when 'collections' is found as the content_type_name, that will shift the index of every other item in the array down 1.
In the Angular forEach loop, it starts on index 0, removes it, then moves on to index 1, which is now the final element in the array since one was just removed. Basically it's skipping over the second element.
Your second example, using the for loop, doesn't have this problem since it's moving backwards through the array. So it checks index 2, doesn't do anything, checks index 1, removes it, and moves on to index 0, which it also removes. Hope I worded this well enough...
Maybe you are looking for a filter
$scope.obj = $scope.obj.filter(function(e){
return e.content_type_name == "collections"
});
Then you don't have to remove every single element

Javascript Delete item on sparse array and adjust length error

I have a sparse Array.
I use delete array[id] and I also want to adjust the length of the array after deletions. This is a pseudocode.
....
deleted =0;
...
if (condition) { delete array[id]; deleted++;}
...
array.length-=deleted;
Ok. I dont know what happen, the array has the expected length but ... it is empty!
Any idea what is happen?
Right way to delete an element from sparse array is :
arr.forEach(elm,index){
//delete index element
delete arr[index]
}
This removes the element but leaves the array size same
If you really want to do it manually and don't care about the order of items, the following is much faster than splice, but this messes up your order:
array[id] = array[array.length-1]; // copy last item to the index you want gone
array.pop(); // rremove the last item
The length of the array is automatically correct.
If you want to keep your order do what zerkms said and use splice
array.splice(id, 1);
The first parameter is the index from where you start. The second parameter is how many items you delete.
The length of the array is also correct.

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

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.

Categories