This question already has answers here:
Why doesn’t deleting from a Javascript array change its length?
(6 answers)
Closed 8 years ago.
arr = [
{
id:1
},
{
id:2
}
]
This is an example object structure. I want to delete first object in this array.
delete arr[0];
Resulting structure is
[
{
undefined * 1
},
{
id:2
}
]
I have searched a lot and found that deleting an entire object will lead to dangling pointer problems. But i want resulting array to have only one object after deletion. Is there any other way to achieve this?
EDIT
How to do if the object is neither first nor last?
You need to create a shorter array instead. To remove the first element, just slice the array:
arr = arr.slice(1);
When the previous array is discarded the first element will also be discarded.
You could, as an alternative to Array.prototype.slice(), use array.prototype.shift(), which simply removes the first element of the array:
arr = [
{
id:1
},
{
id:2
}
];
console.log(arr); // [Object, Object]
arr.shift();
console.log(arr); // [Object]
References:
Array.prototype.shift().
Array.prototype.splice().
The only way to delete anything from an array is to resize it
arr = arr.slice(1)
Related
This question already has answers here:
Strange behavior of an array filled by Array.prototype.fill()
(9 answers)
Array.prototype.fill() with object passes reference and not new instance
(7 answers)
Modifying a copy of a JavaScript object is causing the original object to change
(13 answers)
Closed 1 year ago.
I faced a strange situation when I tried to create an array of arrays via fill and then I tried to add some value to the first child I saw all other nested arrays receive this value as well.
I have an idea why it could happen. It looks like the fill property uses the same object of all 3 nested 'places\items' and now each item is the reference to the single Array.
Also, I tried to use the .fill(new Array()) instead of the literal expression but I had the same result.
I'm not sure if I'm right so fix me, please, if I missed something. Thanks
// an amount of the required output arrays
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill([]);
cols[0].push({id: 1})
The expected result:
[
[
{
"id": 1
}
],
[],
[]
]
the actual result:
[
[
{
"id": 1
}
],
[
{
"id": 1
}
],
[
{
"id": 1
}
]
]
P.S. What is the right way to achieve the result I want to have? Should I just use the for cycle and populate the parent array via the children or maybe some nicer way exists?
From the fill docs at MDN:
If the first parameter is an object, each slot in the array will reference that object.
This means that you get an array of references to the same array (which is an object as well).
As to how to do it in a nicer way... that depends on what you want to achieve. Why do you need the array of arrays? Will they all have a fixed length?
Arrays are passed down by reference this makes it not that great for the fill method. Though you can fill it with a placeholder value and then map those to an array.
const requiredArrays = 3;
const cols = new Array(requiredArrays).fill('').map(() => []);
cols[0].push({id: 1})
console.log(cols);
EDIT: As pointed out in the comments, a better solution:
const requiredArrays = 3;
const cols = Array.from({length: requiredArrays}, () => []);
cols[0].push({id: 1})
console.log(cols);
This question already has answers here:
How to select nth item inside the object
(2 answers)
Closed 2 years ago.
If I were to have a Json file that looked something like this:
{
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
and I wanted to get the value of the third number (three) using JavaScript. Instead of doing...
jsonObject.numbers.thirdnum
Is there a way I can select that value using some sort of children or index method? for example something kind of like this...
jsonObject.numbers.children[2]
First you have to convert your JSON to JavaScript:
const object = JSON.parse(string_of_json);
Then you can get an array of an objects properties, keys, or both with the appropriate methods on the Object class.
Object.keys(object.numbers)[2];
Object.values(object.numbers)[2];
Object.entries(object.numbers)[2];
Since order isn't guaranteed, this isn't generally useful unless you want to do something to every item item you get back.
If you want to access them by position then you should usually write your orignal JSON to use an array instead of an object.
{
"numbers": [ "one", "two", "three", "four", "five" ]
}
You can use Object.values to convert the values to an array and attach the index.
obj = {
"numbers":{
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
}
console.log(Object.values(obj.numbers)[3])
After you parse JSON it became Object, so
const obj = {
"numbers": {
"firstnum":"one",
"secondnum":"two",
"thirdnum":"three",
"fourthnum":"four",
"fifthnum":"five"
}
};
console.log(obj.numbers[Object.keys(obj.numbers)[2]]);
This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 2 years ago.
I have a for loop and I would like to tap into an object inside the array I am looping. Specifically I would like to tap into the "Name" section of my objects to only console.log the names, not the whole array. This is the code... I am doing this with Mongoose but I don't think it has anything to do with my problem, I just wanted to add it tho.
const newCustomerNum2 = new customerList({
name: "John",
age: 32
});
customerList.find(function(err, customers) {
if (err) {
console.log(err);
} else {
for (var i = 0; i<customers.length; i++){
console.log(customers.name);
}
}
});
What is happening in your for loop, is that you are looping over the indices of your array.
Let's say you array has 3 elements, the for loop would be called with i = 0, then i = 1, then i = 2.
This index can be used to reference an object in your array.
When you are calling customers.name you are trying to access the property name on the array rather than the data in it.
If you want to access the objects inside your array, use the subscript expression:
customers[i] where 0 < i < customers.length.
That way, you can use console.log(customers[i].name) in your loop.
In addition, you could simply use the for ... of expression, which iterates over the elements of an array:
for (let customer of customers) {
console.log(customer.name);
}
This question already has answers here:
JavaScript: How to join / combine two arrays to concatenate into one array?
(3 answers)
Closed 4 years ago.
i tried to push an array to other array in specific order
with this javascript code :
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
console.log(arr1.splice(0,-1,arr2));
its reutn [];
my desire rusult : ["1","2","3","A","B","C","D","F"]
please any body show me how to achieve my desire result with splice function
ps : i can achieve this with loop
Thx
EDIT: sorry, My question was misleading. This is my actual condition:
arr1 :[["A","B","C"],["D","E","F"]]
arr2 :["1","2","3"]
Expected output : [["1,"2","3","A","B","C"],["1","2","3","D","E","F"]]
I have tried:
arr1.map(function(e) {
return e.splice(0, -1, arra2)
});
but I got: [],[]
You can use Spread syntax like this const result = [...arr2, ...arr1];
Code:
const arr1 = ["A","B","C","D","E","F"];
const arr2 = ["1","2","3"]
const result = [...arr2, ...arr1];
console.log(result);
Since other solutions creates a new array as result, we could use an approach by modifying in-place your original array by using unshift method in combination with spread syntax.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
arr1.unshift(...arr2);
console.log(arr1);
Do you have to use splice? The concat methods does exactly what you want to achieve.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
var result = arr2.concat(arr1);
console.log(result);
// If you're okay with using spread syntax (doesn't work in IE), you could just:
console.log([...arr2, ...arr1]);
Spliche works for the given array and if you like to add the values of arr2 at the beginning of the array, then you could splice the array with a spreaded array.
Array#splice returns the array which ts taken out of the given array by the count of the second parameter, which id zero here, and not -1 whcih makes no sense.
var arr1 = ["A", "B", "C", "D", "E", "F"],
arr2 = ["1", "2", "3"]
arr1.splice(0, 0, ...arr2); // returns []
console.log(arr1);
From docs, return value of Array.splice is
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.
It will not return the updated array and as you are not removing any element, it will return an empty array.
To add some entries using splice at a particular index, you can try following.
var arr1=["A","B","C","D","E","F"];
var arr2=["1","2","3"]
arr1.splice(0,0, ...arr2);
console.log(arr1);
I have an object which has duplicate values so i used delete new_object[1] to delete the value but when I see this in console its showing undefined in object 0800
["293", undefined, "298", "297"]
You should use
arr.splice(index, 1);
delete only removes the element, but keeps the indexes. This question is similar in nature and provides more information.
I think you should use splice
a = ["1","2","3"];
a.splice(1,0)
console.log(a) //["1","3"]
var test = [1,2,3,4];
delete test[1];
now if you print the test variable, you will get
=> [ 1, , 3, 4 ]
that is why you have got undefined
like everyone here is answering, you should use splice
test.splice(1,1);
and now print the test variable will give you
=> [ 1, 3, 4, 5 ]
you need to use splice() in order to remove the value from the array. What you are doing is simply setting it to undefined.
var myArray = ['295', '296', '297', '298'];
// removes 1 element from index 2
var removed = myArray.splice(2, 1);
// myArray is ['295', '296', '298'];
// removed is ['297']
Reference from Array.splice
The splice() method changes the content of an array by removing
existing elements and/or adding new elements.