Deleting JavaScript array element shows undefined [duplicate] - javascript

This question already has answers here:
How can I remove a specific item from an array in JavaScript?
(141 answers)
Closed 7 years ago.
I have a JavaScript array with objects and an array having some Ids. What I want is to compare the objects in the array with the array of ids and if any id is found in an object, I want to remove that element from the array. Doing this the result shows undefined in place of deleted element.
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}]
var arr = ["2","5"];
for (var i = 0; i < data.length; i++) {
for(var j=0;j<arr.length;j++){
if (arr[j]==data[i].id ) {
delete data[i];
}
}
}
The result shows [undefined,object object,object object,undefined]. Is there any way to get only [object object,object object]?

use splice instead of delete
loop array from length-1 to 0, otherwise you'll miss deal with some data.
var data = [{"name": "John_Smith","val":"3","id":"2"},{"name": "Peter_Adams","val":"2","id":"3"},{"name": "Priya_Shetye","val":"1","id":"4"},{"name": "Sara_Brown","val":"4","id":"5"}];
var arr = ["2","5"];
for (var i = data.length-1; i >= 0; i--) {
for(var j = 0;j < arr.length;j++){
if (arr[j]==data[i].id ) {
data.splice(i,1);
}
}
}
console.log(data);

Related

How to create a empty two dimensional array in Javascript with for loop? [duplicate]

This question already has answers here:
How can I create a two dimensional array in JavaScript?
(56 answers)
Closed 2 years ago.
i know how to create a one dimensional empty array like this:
var data = [];
var length = 100;
console.log(data);
for(var i = 0; i < length; i++) {
data.push(' ');
}
but how do i make the same thing, but two dimensional?
Your data is not an empty array, it is an array of 100 blanks/spaces.
If that's what you mean, then:
var length=100;
var data=[];
for(var i=0; i<length; i++) {
var innerData=[];
for(var j=0; j<length; j++) {
innerData.push(' ');
};
data.push(innerData);
}
I guess what you need is an array of arrays in that case you just fill the outer array with the number of arrays you want, you could use the for loop
var data = [];
var length = 100;
for(var i = 0; i < length; i++) {
data.push([]);
}
console.log(data)
or use fill instead as it's simpler, but the difference is all the arrays created will have same reference as the first array
array=Array(10).fill([])
console.log(array)

How can I extract values from a array JSON? [duplicate]

This question already has answers here:
How can I access and process nested objects, arrays, or JSON?
(31 answers)
Closed 3 years ago.
I have this JSON:
[[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]]
CODE JS:
var giftLabel = window.checkout.giftLabel; // return json
var array = JSON.parse("[" + giftLabel + "]"); // transform in a array
for(var i = 0; i < array.length; i++) {
for(var j = 0; j < array[i].length; j++) {
var parse = JSON.parse(array[i][j]); //this line not working
console.log(parse.product_name); //this line not working
}
}
I want to extract the values from this JSON and choose an example
OUTPUT:
prod-1
http:\\www.google.com
Can you please tell me where I am wrong and why can't I extract the values from JSON correctly?
var parse = array[i][j];
output = Object.values(parse)
output = ['prod-1', 'http:\www.google.com']
Object.values will return an array of all the values inside the passed object
let d = [
[{
"product_name": "prod-1",
"product_url": "http:\\www.google.com"
}]
]
for (let i = 0; i < d.length; i++) {
for (let j = 0; j < d[i].length; j++) {
if(typeof d[i][j] != "undefined"){
console.log(d[i][j]["product_name"]);
console.log(d[i][j]["product_url"]);
}
}
}
It seem your [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]] is already in JS object. So you can always access it via
var x = [[{"product_name":"prod-1","product_url":"http:\\www.google.com"}]];
console.log(x[0][0].product_name);
Or if you value is in JSON text, then parse it first:
var x = JSON.parse("you json text");
then continue as above example.
Here's the working in loop:
var x = JSON.parse("json text");
x.forEach(function(i){
i.forEach(function(ii)){
console.log(ii.product_name);
}
});

For Loops for Name Property [duplicate]

This question already has answers here:
From an array of objects, extract value of a property as array
(24 answers)
Closed 4 years ago.
I am a very beginner with Javascript and I'm working on a question from my Mentor that I'm totally stuck on:
Create a function that accepts one parameter. This parameter will be an array of objects. Each object will have 1 property name. The function should return a new array that is populated with the name properties from the objects.
Example
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
//returns ['Tacos', 'Burritos', 'Enchiladas']
I do not know how to make a for loop that will iterate over any array put into the function parameters. I've only done ones that have defined arrays.
This is what I have:
function namesFunction(){
var arr = [];
for (i = 0; i < arr.length; i++){
console.log(arr[i].name);
}
}
namesFunction([{name: 'Tacos'},{name: 'Burritos'},{name: 'Enchiladas'}]);
Any help is appreciated! Thank you!
You're writing a function that takes an array:
function mapObjectsToNames(array) {}
And you want it to return a new array:
function mapObjectsToNames(array) {
var result = [];
return result;
}
You're going to have to iterate over each element in the array:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
}
return result;
}
You already were logging the name property from each element:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
console.log(array[i].name);
}
return result;
}
Now you'll want to add the name to the new list:
function mapObjectsToNames(array) {
var result = [];
for (var i = 0; i < array.length; i += 1) {
result.push(array[i].name);
}
return result;
}

Cannot set property '0' of undefined , creating multidimensional array in for loop [duplicate]

This question already has answers here:
jQuery Multidimensional Array (dynamic key) - Cannot set property of undefined
(2 answers)
Closed 5 years ago.
I am trying to group objects by key 'pokoj'.
var array = [];
for (var i = 0; i < events.length; i++)
{
array[events[i]['pokoj']][i] = events[i];
}
console.log(array);
You have to check first if the subarray exists and if not, create it:
var array = [];
for (var i = 0; i < events.length; i++) {
if (!(events[i]['pokoj'] in array)) {
array[events[i]['pokoj']] = [];
}
array[events[i]['pokoj']][i] = events[i];
}
console.log(array);

Append an array to another array in JavaScript [duplicate]

This question already has answers here:
Closed 10 years ago.
This question is an exact duplicate of:
How to append an array to an existing JavaScript Array?
How do you append an array to another array in JavaScript?
Other ways that a person might word this question:
Add an array to another
Concat / Concatenate arrays
Extend an array with another array
Put the contents of one array into another array
I spent some time looking for the answer to this question. Sometimes the simplest ones like these are the hardest to find answers to, so I am adding the question here hopefully with plenty of key words and phrases as per this blog post. Please feel free to answer this question with any other helpful information or edit the key words and phrases below.
If you want to modify the original array instead of returning a new array, use .push()...
array1.push.apply(array1, array2);
array1.push.apply(array1, array3);
I used .apply to push the individual members of arrays 2 and 3 at once.
or...
array1.push.apply(array1, array2.concat(array3));
To deal with large arrays, you can do this in batches.
for (var n = 0, to_add = array2.concat(array3); n < to_add.length; n+=300) {
array1.push.apply(array1, to_add.slice(n, n+300));
}
If you do this a lot, create a method or function to handle it.
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
and use it like this:
array1.pushArrayMembers(array2, array3);
var push_apply = Function.apply.bind([].push);
var slice_call = Function.call.bind([].slice);
Object.defineProperty(Array.prototype, "pushArrayMembers", {
value: function() {
for (var i = 0; i < arguments.length; i++) {
var to_add = arguments[i];
for (var n = 0; n < to_add.length; n+=300) {
push_apply(this, slice_call(to_add, n, n+300));
}
}
}
});
var array1 = ['a','b','c'];
var array2 = ['d','e','f'];
var array3 = ['g','h','i'];
array1.pushArrayMembers(array2, array3);
document.body.textContent = JSON.stringify(array1, null, 4);

Categories