Why can't array elements use push methods in JavaScript? - javascript

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)

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);

How to remove objects with the same key and value pair in arrays

I've looked through many stack overflow questions, but none seem to quite answer my question. I have an array of objects, which I would like to reduce by deleting all objects where the key and value are the same.
So my array of objects would be:
[{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
The end result should be:
[{a:1},{a:2},{c:3},{b:1},{c:4}]
I've tried using filer and map, but I can only get the first object in the array, rather than all the objects that have different key/value pairs in the array. I've also tried using filter and findIndex, but with the same problem.
I also can't filter the objects before pushing them into the array.
Can someone point me in the right direction?
You can compare the two items using JSON.stringify(). We then add to a new array using reduce, if it is in the array we don't add it otherwise we do add it.
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = array.reduce((res, itm) => {
// Test if the item is already in the new array
let result = res.find(item => JSON.stringify(item) == JSON.stringify(itm))
// If not lets add it
if(!result) return res.concat(itm)
// If it is just return what we already have
return res
}, [])
console.log(unique)
Alternatively you could use a Set (as Fissure King metions) to make a unique list of items like this:
const array = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}]
let unique = [...new Set(array.map(itm => JSON.stringify(itm)))].map(i => JSON.parse(i))
console.log(unique)
Assuming that all your object are of different types(different properites) and are not complex in nature i.e., not nested objects..
Create a array list(which will act as multi dimensional array).
let uniqueArr = [];
Loop through your array which contains duplicates with Arr.forEach();
Get property of the object using
Object.getPropertyNames(item);
Check wether this type of object type already exists in your uniqueArr ,if not add the property type.
uniqueArr.push({property:[]});
If the property already exists in the uniqueArr, check whether the current property value exits in the property array inside uniqueArr.
If the property doesn't not exist add the new property to the respective property array.if the property exits skip and run the loop for next object.
Once loop completed, create resultArr with the help of the
uniqueArr.
Sample : uniqueArr [ {a:[1,2]}, {b:[1]}, {c:[3]} ];
var a = [{a:1},{a:2},{c:3},{b:1},{a:1},{c:3},{c:4},{a:1}];
var newData = [];
a.map(ele=>JSON.stringify(ele)).forEach(ele=>{
if(newData.indexOf(ele) === -1){
newData.push(ele)
}
});
newData.map(ele=>JSON.parse(ele))
console.log(newData);

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)

How to update an object property array value?

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]);
}
:)

Categories