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);
Related
var strArr = []
strArr[0].push("someThing Text")
console.log(strArr)
Error: Cannot read properties of undefined (reading 'push')
var strArr = []
strArr[0] = "someThing Text"
console.log(strArr)
Array ["someThing Text"]
What's the difference between the two? Why can't array elements use push methods?
You are trying to push into an array at index 0 inside another array.
var strArr = []
strArr.push("someThing Text")
console.log(strArr)
If you wanted your code to work, you would need to do this.
var strArr = [ [] ] // an array in an array
strArr[0].push("someThing Text")
console.log(strArr)
Simply put, push is an array method. that means it only applies to an array (I look forward to a correction as I am a learner too).
Therefore, push will only apply/operate on an array element if the element is an array as well. Another way to grasp this is to note that elements in an array may be of different data types. Each data type has a different (predefined) set of operations/methods that can be applied to them. push is a predefined method that can be applied only to an array or array element(s) that is/are of the type array.
See the snipped below:
const myArr = ['Hello', 'World', ['Javascript', 'Python', 'PHP'], 100, 'function'];
console.log('Orginal array --> ' + myArr); // Orginal array: Hello,World,Javascript,Python,PHP,100,function
myArr.push(['Vue', 'Angular', 'React']);
console.log('Updated array --> ' + myArr); // Updated array --> Hello,World,Javascript,Python,PHP,100,function,Vue,Angular,React
myArr[2].push('Java');
console.log('Update myArr[2] ' + myArr); // Update myArr[2] Hello,World,Javascript,Python,PHP,Java,100,function,Vue,Angular,React
When you call an array function, you need to call it on the array itself, i.e. strArr.push("someThing Text"). strArr[0] is an array element, and could be a number, string, boolean, or other data type.
You can however add an array element at a specific point in an array, which is sort of what it looks like you were trying to do, with Array.splice(). The parameters are:
index where array element should be inserted
number of items (starting at index) you want to delete
the actual elements you want to insert
var strArr = ["foo", "bar"]
strArr.splice(1, 0, "someThing Text")
console.log(strArr)
You are using the push method on an array element, not the array.
You should use strArr.push()
You are trying to add the element in a specific position using push() method. But the push() method is used to add one or multiple elements to the end of an array. An object can be inserted by passing the object as a parameter to this method. The object is hence added to the end of the array.
array.push(objectName)
var strArr = []
strArr.push("someThing Text")
console.log(strArr)
I have been watching PluralSight's Rapid JavaScript Training by Mark Zamoyta and I came across this. He showed these two examples. I've been trying to wrap my head around it, but still could not understand.
How is it able to capture the length of the entries after the array was created using new Array() method, seeing that it returned a blank array []. If it's blank like this [], shouldn't it return -1?
var entries = [1,2,3,4,5];
entries.length
=> 5
entries
=> [ 1, 2, 3, 4, 5 ]
var entries = new Array(5);
entries.length
=> 5
entries
=> []
var myArray = new Array(5);
When you define an array by passing the constructor an integer like above, memory is allocated for 5 slots in the array. If you examine the array, you will find:
console.log(myArray[1]);
=> undefined
console.log(myArray.toString);
=> ,,,,
As you can see, there are indeed five elements in the array, each of them undefined. So your array isn't "blank."
It is probably bad practice to initialize an array in this manner, as there just isn't a good use case for it. Pushing to the array will yield:
myArray.push("value");
console.log(myArray.toString);
=> ,,,,,value
...which is never what you want. I would advise initializing the array like below and forget that passing an integer to the constructor is even an option:
var myArray = [];
The length property of an array in JS is not calculated on the fly - it can also be set manually via the constructor or an assignment, and it's updated as objects are added or removed (Spec):
Specifically, whenever a property is added whose name is an array index, the length property is changed, if necessary, to be one more than the numeric value of that array index[.]
It's a plain property that's kept up-to-date, not a calculation. Using the constructor new Array(5) initializes an array with length set to 5. You can also set it manually, which fills in undefined or truncates the array as needed:
var arr = [];
arr.length = 3;
// arr is now [undefined, undefined, undefined]
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.
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)
If I have an object defined as:
var myObj={};
Then, I update this object with:
myObj['fruit']=['apple', 'orange'];
Later, I would like to append "[banana, melon]" to myObj['fruit'], that's update myObj to
['apple','orange','banana','melon']
what is the most elegant way to update 'fruit' attribute value of myObj in my case? That's update array by appending a new array.
--------EDIT-------
I need a way to append array as one variable, not extract each element of the appended array and push. e.g. oldArray append with newArray = final array
JavaScript has a built in Array.push()
myObj["fruit"].push( 'banana', 'melon' );
There are a few ways to approach appending an array. First up, use apply() to call push with the array as individual arguments:
var toAppend = ['banana', 'melon'];
// note [].push is just getting the "push" function from an empty array
// the first argument to "apply" is the array you are pushing too, the
// second is the array containing items to append
[].push.apply( myObj["fruit"], toAppend );
Also, you could concat() the arrays, however concat doesn't modify the original array so if you have other references they might get lost:
myObj["fruit"] = myObj["fruit"].concat( toAppend );
If you don't want to push, then concat :)
I would suggest to iterate the array items that you want to push, by doing this:
var newObj = ["banana", "melon"];
for (var i in newObj)
{
myObj['fruit'].push(newObj[i]);
}
:)