After using push(), array is logged as a number - javascript

I'm trying to get an array of some images to flip through. The first set need to be in descending order, while the second set need to be in ascending order, so I have written this:
var flipArray = [];
function createFlipArray(older, newer){
flipArray = $("#"+older).children();
flipArray = flipArray.get().reverse();
flipArray = flipArray.push($('#'+newer).children());
console.log(flipArray);
loopThroughImages();
}
When I push the second set onto the first set, it logs the array as 4, even though there are 6 items in the whole array.
If I log the array after I populate it with the older children, it returns with HTML objects, which I expect to see after I push the newer children on.
Any suggestions?

.push modifies the array in-place. It does not return a new array, it returns the array's new length.

Array.prototype.push returns the array's new length. It modifies the original array. Remove the flipArray = before it.

Related

Issue when splicing array of objects

I have a vue application that gets a set of objects from an external REST API.
In a component, I sort and filter the object into an array of objects based on a field called rank, like this:
let myResults = _.orderBy(this.search_result, 'rank', 'desc').filter(service => (service.rank >= 5) ? service: "");
I then need to move a single element/object to the end of the list before rendering it, however, when I tried to do this:
let index = myResults.findIndex(e => e.name === 'Target Element');
myResults.push(myResults.splice(index,1));
It didn't work; It pushed an empty element back to the list. Eventually, I got it working by doing the following:
myResults.push(myResults.splice(index,1)[0]);
I noticed the splice was creating an array that looked like [object, object] with all the target object in the zero index object.
I don't really understand why this happened. Have I done something to the original object somewhere or is this a vue thing?
JavaScript Array.prototype.splice() returns an Array.
Return value
An array containing the deleted elements.
If only one element is removed, an array of one element is returned.
If no elements are removed, an empty array is returned.
Since an Array is returned, you're .push()-ing and Array into an existent array. As you noticed correctly, you need to extract that one Object using removedItems[0], making
myResults.push(myResults.splice(index,1)[0]);
or equally
// Remove from array 1 item
const removedItems = myResults.splice(index, 1); // Array of removed items
// Get the first Object from array
const item = removedItems[0]; // Object
// Append one Object
myResults.push(item);
the correct approach.

How can you change the index of multiple array objects?

Problem:
How can you change the index of multiple objects within an array of 100 objects?
In my case I would like to push them to the end of the array.
I have fetched a json array that contains over 100 objects, each with their own properties including a number property for each object that can be used to filter.
Attempts
I tried populating a variable using .splice to remove the specific array objects. Although .push wont accept that variable.
Also tried .slice but couldn't push the sliced objects to the end.
Also tried to loop through the original array using a for loop and an if statement with the condition of each objects "number" property.
Code:
(the fetch is a success, only issue is the restructure of the array itself)
elementsArray.value = await data.json();
let removedElements = elementsArray.value.slice(56,71);
elementsArray.value.push(removedElements);
With slice, the original array will not be modified. Use splice instead.
push accepts one or more elements. so use spread syntax
const animals = ['ant', 'bison', 'camel', 'duck', 'elephant']
const removedElements = animals.splice(2, 2)
animals.push(...removedElements)
// some other alternatives
// Array.prototype.push.apply(animals, removedElements)
// animals.concat(removedElements)
console.log(animals)
Here is a way you can use splice to append a to b but as in the commentarys mentioned for this use case .concat() or .push(...otherArray) is the better choice
let a = [1,2,3],
b = [4,5,6];
a.splice(0, 0, ...b);
console.log(a);

Empty Array in javascript

I created an object which contains an array.
I noticed that when I dont enter any values into the array, it still has one - its size,
So how can I check if the array is actually empty?
Here's how I'm creating the array:
array = { text:[10] }
The size of the array is not an array entry (aka array "element"). It is a property, length, but it's not an entry. An empty array is exactly that: empty.
The code you posted in a comment:
array = { text:[10] }
does not create an empty array. It creates an array of length 1 with the entry 10 in it.
If you want to create an empty array with a specific length, you can't do that in a single statement with an array literal ([]). You have two ways you can do it:
Using an array literal and assigning to length:
var a = [];
a.length = 10;
or using new Array:
var a = new Array(10);
But there's virtually never any reason, in JavaScript, to predefine the length of the array, because standard JavaScript arrays aren't really arrays at all. It does make sense with the new typed arrays (Uint32Array and such), and to do it you have to use the array constructor (new Uint32Array(10)).

Javascript syntax: var array = [].push(foo);

Where foo is a defined variable, why is it that the following code:
var array = [].push(foo);
when outputted, equals 1?
From my tests, outputting array will simply output the length of the array.
So the code:
var array = [10,20].push(foo);
would give a value of 3.
As a related question (and to clarify what my code intended to do), why does this not intuitively do what it appears to do, ie:
var array = [];
array.push(foo);
where outputting array gives the expected result of [foo]?
When you use push method it returns length of array. So when you do:
var array = [10,20].push(foo);
you get [10, 20, foo] length of this array is three. But as you say var array it stores returned length from push method in this variable.
Array.prototype.push() always returns the new number of elements in the array. It does not return this instance or a new Array instance. push() is a mutator actually changes the contents of the array.
instead you can try
var array, foo = 30;
(array = [10,20]).push(foo);
console.log(array)
push is a function and it returns an integer representing the length of the array.
Imagine the definition of this function as
int push(object obj);
When you do this:
var array = [].push(foo);
You are actually running the function and returning the value.
Because the return value of push is the new length of the array Documentation and examples.
In your second example, you cited outputting the array, which is going to give you the new array in both cases. However, the returned result of your second case is the new array length as well
var array = [];
array.push(foo); //If you do this in the console, you'll see that 1 gets returned.
console.log(array); //While this will print out the actual contents of array, ie. foo
The definition of push() method including two parts in javascript: Part 1: it adds one or more elements to the end of an array, part 2: it returns the new length of the array.
I think you are missing the part 2 in your understanding of this method.

push associative array error?

I have to push elements in an associative array from another array after some processing and I'm doing something this:
for(var i in this.aNames) {
var a = this.aNames[i];
// some processing on a
aList[i] = a;
aList.push(i);
}
But it's not giving me the proper array.
EDIT :
Here aNames is an associative array like this
'1232':'asdasdasd',
'6578':'dasdasdas'
...... and so on of about 100 elements.
I'm using for here as I want to do some changes in every element of the array.
Then I'm displaying the result array on the page but it's showing the key value together with the array data.
I.e. it should only display asdasdasd or asdasdasd but it's displaying keys too, like 1232 asdasdasd 6578 dasdasdas.
There are multiple things which may go wrong...
Primarily, make sure that this is pointing to the correct context and that this.aNames is actually returning a complex object (associative array).
Also, what's aList? Is it an array? If it is, push should append your array with the key of the current member (the member's name).
If you want to append the values of the members on your source object, you need to do something like this:
var obj = {name: 'dreas'},
arr = []; // arr is an array
arr.push(obj["name"]); // arr now contains a single element, 'dreas'
In your for..in construct, you are both adding elements to an alleged array (aList) with push but also creating new members on your array (with the subscript notation, aList[i] = "asd" since i in this case (for..in iteration) refers to the member's name).
So, what you need to do is decide if you want to add elements to an array or members to an object, not both.
If you just want to clone an array, use a for loop. If on the other hand you want to clone an object, it's not that trivial because members can also be complex objects containing their own members, and simply doing arr[i] = obj.member will only copy a pointer to arr[i] if member is a complext object, not a value type.
Just to make sure my terminology is understandable:
var anObject = {name: "dreas"},
anArray = [1,2,3];
anObject["name"] <= member (results in "dreas")
anArray[1] <= element (results in 2)

Categories