How to completely remove an empty array in javascript? - javascript

I have searched and searched and cannot find an answer to this, so please accept my apologies if I am being foolish.
I am building an application in node.js that uses JSON files as project configs. I am using the 'fs' module to read the JSON file, which I then parse into a Javascript object. I then amend details within the object before using JSON.stringify to write the data back to the file.
My problem is that I need to delete an array, not just empty it, in order to show the data correctly on my interface:
"floors": [
{
"floorName": "Grd Floor",
"floorNotes": "",
"floorPlan": "Buckley_Grd.jpg",
"floorWidth": "57.392",
"floorHeight": "20.776",
"runs": [
[], *<----I cannot delete these*
[] *<----only empty them*
[
{
"xCoOrd": "37.88235294117647",
"yCoOrd": "59.307359307359306",
"drawingType": "node"
},
{
"xCoOrd": "37.88235294117647",
"yCoOrd": "59.307359307359306",
"drawingType": "node"
},
{
"xCoOrd": "48.549019607843135",
"yCoOrd": "50",
"drawingType": "node"
}
] *<----I don't want to delete the elements in this array*
]
}
I have tried:
.splice(0);
.filter(Boolean);
delete
Everywhere I have looked people seem surprised that one would want to delete an unused array from memory, which is what I beleive I am trying to do. Perhaps there is a way to stringify the object that ignores these empty arrays? Or perhaps I am doing this completely the wrong way?
Many thanks in advance for any advice offered.
EDIT: I should have made clearer that I don't necessarily want to delete all of the elemnets in the array so redeclaring floors.runs =[] unfortunately will not help me.
I have tried:
delete floors[floorID].runs[runID];
This replaces the array with null which gets written to the file and ruins my reading of the JSON.

Did you try over-writing the 'runs' property of each object? If you said floors[0].runs = [] (or floors[i].runs = [], if you're looping through), then those two empty arrays would no longer show up in your stringify.
Editing my answer, to match the OP edits:
floors.forEach(function(floor){
var newRuns = [];
floor.runs.forEach(function(run){
if (run.length > 0){
newRuns.push(run);
}
})
floor.runs = newRuns;
})
After I assign your object from the OP into a variable and run my code on it, then stringify the result, I get this as a return:
{"floors":[{"floorName":"Grd Floor","floorNotes":"","floorPlan":"Buckley_Grd.jpg","floorWidth":"57.392","floorHeight":"20.776","runs":[[{"xCoOrd":"37.88235294117647","yCoOrd":"59.307359307359306","drawingType":"node"},{"xCoOrd":"37.88235294117647","yCoOrd":"59.307359307359306","drawingType":"node"},{"xCoOrd":"48.549019607843135","yCoOrd":"50","drawingType":"node"}]]}]}
Is that what you're hoping to see? I used this fiddle to produce that result.

If you want remove ALL values from runs array you simply do this:
floors[i].runs = null
If you want remove only the empties
var filled = [];
obj.floors[i].runs.forEach(function(value, i, array) {
if (value.length != 0) filled.push(value);
});
obj.floors[i].runs = filled;

Runs is a property of an object, you can remove items from that array. In your example above floors[0].runs.splice(0,2), should remove both of those arrays I think.

Keeping the same reference
Iterating downwards lets you safely perform operations which decrease the length of an Array by 1 each time
var i, parentArray = obj['floors'][0]['runs'];
for (i = parentArray.length; i >= 0; --i) {
if (parentArray[i].length === 0) parentArray.splice(i, 1);
}
Making a new reference
Creating a new array without the values you don't want can be achieved using .filter
obj['floors'][0]['runs'] = obj['floors'][0]['runs'].filter(function (x) {
return x.length > 0;
});

To remove an object completely you have to remove the reference from the parent. To do this what you can do is create a new Array in which you copy only the references to the non-empty arrays.
I have created this function which should remove all empty arrays. I haven't tested it too much, but this should give you an idea:
function clearEmptyArrays(obj) {
for(var key in obj) {
var arr = obj[key];
if(Array.isArray(arr)) {
// Iterate through all elements and remove empty arrays
var nonEmptyArr = [];
for(var i = 0; i < arr.length; ++i) {
// Recursive call if it's an object inside an array
if(typeof arr[i] === 'object') clearEmptyArrays(arr);
// Save all non-empty arrays or objects inside this one
if((Array.isArray(arr[i]) && arr[i].length > 0) || !Array.isArray(arr[i])) {
nonEmptyArr.push(arr[i]);
}
}
obj[key] = nonEmptyArr;
return;
}
// Recursive call if it's an object
if(typeof arr === 'object') {
clearEmptyArrays(arr);
}
}
}
You can call it like this: clearEmptyArrays(myObj); and will update the Object in-place.
Demo: https://jsfiddle.net/zeo7dauh/

Related

How to extend an array with new array without declaration

I am working on project where I need to maintain an array from json data returned from API, json can have tree, I have following code which is working fine but I wan to remove if conditions before assigning values to array elements
// data contains json
let newArray = []
for(let d in data){
for(let x in data[d]){
if(typeof(newArray[d]) === 'undefined'){
newArray[d] = []
}
if(typeof(newArray[d][data[d][x]['id']]) === 'undefined'){
newArray[d][data[d][x]['id']] = []
}
newArray[d][data[d][x]['id']]['price'] = data[d][x]['price']
newArray[d][data[d][x]['id']]['discount'] = data[d][x]['discount']
}
}
In above code I have to check the array first and declare it as array if its not otherwise it returns undefined error, is there any way to get rid of there conditions and extend array as per requirement ?
You can you new ES6 spread operator like this
newAraay[d] = [...newArray,...Array(data[d][x]['id']),[...Array('price',data[d][x]['price'])]]
Like here in this snippet I am directly doing abc[1][3][4] = "new value" without explicitly initialising them
let abc = [];
abc[1]= [...abc,...Array(3),[...Array(4),'new inserted value']]
console.log(abc);
newArray[d] = newArray[d] || []
You can understand this operation in this post
Or use Lodash Library
https://lodash.com/docs/4.17.11#set

Deleting a specific key within an array

Thank you for stopping by. I'm a but confused in regards to my code. I've tried different variation but continue to not be able to just delete a single key from an array of obs. For example:
var cart = [];
var obj = {};
var newObj = {};
obj["mcdonald"] = "food"
obj["starbucks"] = "coffee"
newObj["new"] = "books"
newObj["old"] = "books"
cart.push(obj);
cart.push(newObj)
Now we want to remove just a single key. Let say for example just "new" key with value "books" from newObj object instead of the entire object. Every single time I get the entire object being deleted instead of just a single key. Can someone please tell me what I may be missing or where I'm going wrong. This is a homework I'm working on. I notice the test passes since we need to remove the item we place into the parameter but I want to be able to learn it the right way. Meaning, move a single key not the entire object.
function removeFromCart(itemName){
for(var newArr in cart){
if (cart.hasOwnProperty(newArr)) {
var item = Object.keys(cart[newArr])[0]
if (item === itemName) {
var index = cart.indexOf(itemName)
cart.splice(index, 1)
} else {
alert('That item is not in your cart.')
}
}
}
return cart
}
To better understand this, I'm going to create an example data structure:
var cart = [
{ "mcdonald": "food", "starbucks": "coffee" }, // obj
{ "new": "book", "old": "book" } // newObj
];
So now if I want to remove the item with key == 'new', it's easy to see that we need to iterate over all the objects in the array, and then delete any keys that match what we're looking for.
function removeItem(itemKey) {
cart.forEach(function(obj) {
delete obj[itemKey];
return obj;
});
}
I would also encourage you to write pure functions, as that will help you better understand (the coding intention) and debugging.

Javascript: Find douplicated values from array with keys

Title is pretty much self explanatory...
I want to be able to find duplicated values from JavaScript array.
The array keys can be duplicated so I need to validate only the array values.
Here is an example :
var arr=[
Ibanez: 'JoeSatriani',
Ibanez: 'SteveVai',
Fender: 'YngwieMalmsteen',
Fender: 'EricJohnson',
Gibson: 'EricJohnson',
Takamine: 'SteveVai'
];
In that example:
the key is the guitar brand
the value is the guitar player name.
So:
If there is duplicated keys (like: Ibanez or Fender) as on that current example that is OK :-)
But
If there is duplicated values (like: EricJohnson or SteveVai) I'm expecting to get (return) that error:
EricJohnson,SteveVai
You can't have associative arrays in Javascript. You can create an array of objects, like:
var arr=[
{Ibanez: 'JoeSatriani'},
{Ibanez: 'SteveVai'},
{Fender: 'YngwieMalmsteen'},
{Fender: 'EricJohnson'},
{Gibson: 'EricJohnson'},
{Takamine: 'SteveVai'}
];
Then you'll need a for...in loop to go over every object in the array, create a new array of values and check that for duplicates, which is also not very straightforward - basically you'll want to sort the array and make sure no value is the same as the one after it.
var arrayOfValues = [];
arr.forEach(function(obj){
for(var prop in obj)
arrayOfValues.push(obj[prop]);
});
arrayOfValues.sort(); // by default it will sort them alphabetically
arrayOfValues.forEach(function(element,index,array){
if(array[index+1] && element==array[index+1])
alert("Duplicate value found!");
});
First of all, object keys can not be repeated.
This means that:
({
"Fender": "Jim",
"Fender": "Bob"
})["Fender"]
Would simply return: "Bob".
However, I did make a code that could allow you to find duplicates in values, but as I said, the key will have to be unique:
var arr = {
Ibanez: 'EricJohnson',
Fender: 'YngwieMalmsteen',
Gibson: 'EricJohnson',
Takamine: 'SteveVai',
"Takamine2": 'SteveVai'
};
function contains(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
}
var track = [];
var exists = [];
for (var val in arr) {
if (contains(track, arr[val])) {
exists.push(arr[val]);
} else {
track.push(arr[val])
}
}
alert(exists)
You can see it working here: http://jsfiddle.net/dr09sga6/2/
As others have commented, the example array you provided isn't a valid JavaScript array. You could, however, keep a list for each guitar type:
var mapping = {
Ibanez: ['JoeSatriani','SteveVai'],
Fender: ['YngwieMalmsteen','EricJohnson']
Gibson: ['EricJohnson'],
Takamine: ['SteveVai']
];
Or a list of each guitar/musician pair:
var pairs = [
['Ibanez','JoeSatriani'],
['Ibanez','SteveVai'],
['Fender','YngwieMalmsteen'],
['Fender','EricJohnson'],
['Gibson','EricJohnson'],
['Takamine','SteveVai']
];
Your solution is going to depend on which pattern you go with. However, in the second case it can be done in one chained functional call:
pairs.map(function(e) {return e[1]}) // Discard the brand names
.sort() // Sort by artist
.reduce(function(p,c,i,a){
if (i>0 && a[i]==a[i-1] && !p.some(function(v) {return v == c;})) p.push(c);
return p;
},[]); //Return the artist names that are duplicated
http://jsfiddle.net/mkurqmqd/1/
To break that reduce call down a bit, here's the callback again:
function(p,c,i,a){
if (i>0
&& a[i]==a[i-1]
&& !p.some(function(v) {
return v == c;
}))
p.push(c);
return p;
}
reduce is going to call our callback for each element in the array, and it's going to pass the returned value for each call into the next call as the first parameter (p). It's useful for accumulating a list as you move across an array.
Because we're looking back at the previous item, we need to make sure we don't go out of bounds on item 0.
Then we're checking to see if this item matches the previous one in the (sorted) list.
Then we're checking (with Array.prototype.some()) whether the value we've found is ALREADY in our list of duplicates...to avoid having duplicate duplicates!
If all of those checks pass, we add the name to our list of duplicate values.

Find key from value in associative array containing JSON

I've searched and found a few similar-but-not-quite answers.
I have an array SongList (showing 2 items for brevity...) - the first pair is a key, the second pair is some JSON.
SongList={
song_1:{title:"title of first song",artist:"the artist",mp3:"http://mysite/song1.mp3"},
song_2:{title:"title of second song",artist:"the artist",mp3:"http://mysite/song2mp3"}
...
};
I would like to be able to retrieve the key (song_1 or song_2) given the title in the value.
I will be looping through a temporary array of i items, each item in this array would have a match in SongList and I would save the key (song_1, song_2) in a final array.
You don't have an array, you have an object, containing more objects. Use for in
function findTitle(title) {
for (var key in SongList) {
if (SongList[key].title == title) return key;
}
return false;
}
And then call it!
findTitle("title of first song"); //returns "song_1"
findTitle("BNOT MEEEEEE"); //returns false
Here is an example.
var one = {
a: {b:"MightyMouse", d:2},
b: {b:"MickeyMouse", d:4},
c: {b:"Superman", d:6}
};
for (outerkey in one) {
if (one[outerkey].b === "Superman") {
console.log ("Outerkey = " + outerkey);
}
}
Assuming you are looking for Superman, this prints as expected c.
Thanks everyone, I realize my understanding of Arrays v. Objects was an issue which obviously hindered my Google-Fu. I hope it's ok to post the answer I finally arrived at via guidance here:
(SongList object is described in question above)
This is the eventual function I arrived at for saving the keys of the playlist SongList:
$("#save_playlist_as_keys").click(function() {
var keys = []
for(var i=0; i<myPlaylist.playlist.length; i++){
var playItem = (myPlaylist.playlist[i].title); //this returns the names of the tracks
for (var k in SongList){
if(SongList[k].title == playItem) keys.push(k);//this matches track name to keys
}
}
localStorage.setItem('storedKeys',keys);
});
This seems to be doing what I want for now.

Removing an object from a javascript list of objects

I currently have a list of objects in javascript indexed by a key:
var list = [];
list['a'] = [];
list['a'].push({obj: 'test'});
list['a'].push({obj: 'test2'});
list['b'] = [];
list['b'].push({obj: 'test'});
list['b'].push({obj: 'test2'});
I would list to remove the entry based on the key (a/b)
I have tried the following:
for(var x in list) { delete list[x]; }
that works but it actually leaves an undefined entry in the list.
I have also tried splicing the array, but that does not seems to work in this case.
Any thoughts on how to remove the entry in javascript or jQuery?
Thanks.
The Fix:
After reading some of the comments, i was able to better understand what my list is consistent of. Therefor, i was able to do the removal by doing the following:
delete list.b;
I'm not sure if my list is best way to organize my structure, but doing a delete on the list and treating it like an object property did the trick.
Thanks for all the feedback.
I'll assume list is an object, not an array.
If you want to reset a or (or b it's done the same way)
list.a.length = 0;
If you want to delete an element from a at a known index (let index)
list.a.splice(index, 1);
You're attempting to add the elements to the array object as object properties and not as array elements. You can verify this by inspecting the value of list.length (will be 0).
So when doing something such as the following:
function removeProperty(id) {
if (list.hasOwnProperty(id)) {
delete list[id];
}
}
removeProperty('a');
it's really the same as:
delete list.a;
which is why you think it leaves an undefined 'entry' in the 'list'.
You'll need to use a literal object instead:
var list = {};
list['a'] = [];
...
list['b' = [];
...
which would allow you to use delete and have it behave as you expect. Of course you'll lose the .length property on the array but you never had that anyway.
Create a simple prototype for the Array class
Array.prototype.remove = function() {
// Helper function to remove a single element from a list if exists
item = arguments[0]
if (this.includes(item)) {
index = this.indexOf(item)
this.splice(index, 1)
}
}
// Now we can call
myList.remove(YourObject)
The above code will add the remove method to all your lists, so this will help you not just for objects but also strings, integers, or any data type
var list = {1: [{},{}], 2: [{},{}]};
function removeProperty(obj, prop){
if(obj[prop]){
delete obj[prop];
}
}
removeProperty(list,"1");
console.log(list);
If this quote:
I would list to remove the entry based on the key (a/b)
means you would like to select the list to consider based off the key (a/b), then remove elements in the list (or all of them), you can try this:
var list = [];
list['a'] = [];
list['a'].push({obj: 'test4'});
list['a'].push({obj: 'test5'});
list['b'] = [];
list['b'].push({obj: 'test'});
list['b'].push({obj: 'test2'});
var toRemove = 'test4';
var removeFrom = "a";
var consideredList;
for (var prop in list) {
if (prop == removeFrom) {
consideredList = list[prop];
}
}
//Remove everything from the considered list
consideredList.splice(0, consideredList.length);
//Remove based off value, if you know the property name
// for(var pos in consideredList) {
// if(consideredList[pos].obj == toRemove) {
// consideredList.splice(pos, 1);
// }
// }
I made a Plunker of a few different cases (check the script.js file). There seems to be a bit of confusion on what you are after and hopefully this is helpful to you somehow. Good luck.

Categories

Resources