How to join an associative array into a string - javascript

I am trying to do this now and I wonder if there is a "the most used" method to join an associative array (it's values) into a string, delimited by a character.
For example, I have
var AssocArray = { id:0, status:false, text:'apple' };
The string resulted from joining the elements of this object will be
"0, false, 'apple'" or "0, 0, 'apple'"
if we join them with a "," character
Any idea? Thanks!

Object.keys(AssocArray).map(function(x){return AssocArray[x];}).join(',');
PS: there is Object.values method somewhere, but it's not a standard. And there are also external libraries like hashish.

Just loop through the array. Any array in JavaScript has indices, even associative arrays:
var AssocArray = { id:0, status:false, text:'apple' };
var s = "";
for (var i in AssocArray) {
s += AssocArray[i] + ", ";
}
document.write(s.substring(0, s.length-2));
Will output: 0, false, apple

The implementation of functions like Object.map, Object.forEach and so on is still being discussed. For now, you can stick with something like this:
function objectJoin(obj, sep) {
var arr = [], p, i = 0;
for (p in obj)
arr[i++] = obj[p];
return arr.join(sep);
}
Edit: using a temporary array and joining it instead of string concatenation for performance improvement.
Edit 2: it seems that arr.push(obj[p]); instead of incrementing a counter can actually be faster in most of recent browsers. See comments.

Related

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

Populating an array using a for loop and another array

This is more a learning exercise and nothing super critical - I'm unsure of the best way to Google what I'm looking for, I clicked through a few others suggested answers and didn't find anything that looked super relevant.
I'm wondering if there's a way I can populate an array using another array and a for loop (as opposed to modifying the contents of the existing array in place). What I envision is something like:
var existingArray = ["Thing1", "Thing2", "Thing3"];
let newArray = for (var i=0; i < existingArray.length; i++) {
"Modified string " + existingArray[i];
}
// Output: ["Modified string Thing1", "Modified string Thing2", "Modified string Thing3"]
where I can just create the new array variable and populate it more or less in the same block of code. I know how to do it the maybe more traditional way where I just say:
newArray = [];
oldArray = ["Thing1", "Thing2", "Thing3"]
for (var i = 0; i < oldArray.length; i++) {
newArray.push("Modified string " + oldArray[i]);
}
I'm sorry if this is a somewhat stupid question, I'm just curious if there's a way to do this and if there's any advantage to doing so. It seems like it would be cool to just declare a new array and populate it all with one little chunk of code instead of declaring the new array, then using .push() to populate it.
It would be even better to use .map, since you're transforming one array into another, only one line required:
const existingArray = ["Thing1", "Thing2", "Thing3"];
console.log(
existingArray.map(thing => 'Modified string ' + thing)
);
When you don't have an existing array to .map from, you can still do something similar to create an array immediately by using Array.from - define the length in the first argument, and put the map function in the second argument:
const originalArray = Array.from({ length: 3 }, (_, i) => 'Thing ' + (i + 1));
console.log(originalArray);
newArray = [];
oldArray = ["Thing1", "Thing2", "Thing3"]
for (i in oldArray) {
newArray.push("Modified string " + oldArray[i]);
}
console.log(newArray)

Javascript array object arrays

THis is going to sound like a stupid question but here it goes. I have a js array formatted like so
var locationID = [
{ ID: "ID1", location: "location1" },
{ ID: "ID2", location: "location2" },
{ ID: "ID3", location: "location3" },
];
I am trying to loop through the array
for(i = 0; i < locationID.length;i++){
var object = locationID[i];
}
I want to get both elements from the inner array so the ID and location. would I do this by object[0] or object["ID"] for example.
Also is there a more efficient way to do what I need to do like a for each loop or something along those lines.
Use object.ID or object['ID'].
Objects {} in JavaScript are associative, or named arrays. (Also known as a map in many languages. They are indexed by strings (in this case).
Arrays [], are indexed by integral numbers, starting from 0 and counting up to n-1, where n is the length of the array.
If you want to programmatically go through all the (key, value) pairs in each object, you can use this method.
Quotations (String Literals)
To reiterate my comment below about single and double quotes:
If you're talking about inside the [], no [,they're not important]. JavaScript treats single
quotes and double quotes pretty much the same. Both of them denote
string literals. Interestingly, you can use single quotes inside
double quotes or vice-versa: "I wanted to say 'Hello world!'" would be
a (single) valid string, but so would 'But I accidentally said "Goodbye".
This is an optimized loop based from the book of Nicholas Zackas (YAHOO performance chief). I am performing a cached array length to prevent re-evaluation of array length on every iteration of the loop. Please check jsperf.com. Also, native loop is always faster than method based loops jQuery.each and Array.prototype.forEach. This is also supported on browsers below ie8
var currentItem,
locationInfo = [
{ ID: "ID1", location: "location1" },
{ ID: "ID2", location: "location2" },
{ ID: "ID3", location: "location3" },
];
for (var i = 0, len = locationInfo.length; i < len; i++) {
currentItem = locationInfo[i];
console.log(currentItem.ID);//I prefer this because it shrinks down the size of the js file
console.log(currentItem["ID"]);
}
what you have already will return each of the objects in the JSON as you run the loop. What you need is something like
for(i = 0; i < locationID.length;i++){
var object = {locationID[i].ID, locationID[i].location};
}
Remember properties of objects are accessed by their keys since they are key-value pairs.
For loops are going to be your best bet as far as speed, here's how you'd do it with forEach (IE 9+)
locationID.forEach(function(location, i){
console.log(location['ID'])
console.log(location['location'])
});
jQuery make's it a little easier but runs slower
$.each(array, function(i, item){
});
http://jsperf.com/for-vs-foreach/75
Also here a useful link: For-each over an array in JavaScript?
You can use the forEach method, which make your code more cleaner.
See forEach
locationID.forEach(function(elm){
//Here, elm is my current object
var data = elm;
console.log(data.ID):
console.log(data.location);
});
EDIT :
Then for your second question, you should filter and map methods.
function findNamebyID(id){
//Filter by id and map the data to location
return locationID.filter(function(elm){
return elm.ID === id;
}).map(function(elm){
return elm.location;
})
}
Something as:
var location = locationID.reduce(function(ob, cur) {
ob[cur.ID] = cur.location;
return ob;
}, {});
The result you get is:
Object {ID1: "location1", ID2: "location2", ID3: "location3"}
Meaning you can do:
location.ID1 // location1
location.ID2 // location2
...
an alternative to your loop, would be to use the JavaScript for (.. in ..) since you aren't really using the iterator; it just adds fluff
for(i = 0; i < locationID.length;i++){
var object = locationID[i];
}
could be written as:
for (item in locationID) {
var object = item;
}

How to remove duplicate objects from java script array?

I have two arrays as shown below. I want to remove Array2 elements from Array1. How do I do that?(either in plain java script or using ExtJS)
var Array1 = [];
var Array2 = [];
Array1.push(['eth0'], ['eth1']);
Array2.push(['eth1']);
If you have the array filter function available to you, you can do something like the following:
var filteredArr = Array1.filter(function(val){
return Array2.indexOf(val) != -1;
})
I think this will only be supported in newer browsers, though. It's an elegant way to handle the situation, so you may want to take a look at a library like UnderscoreJS which will include filtering, defaulting to the native implementation if available.
If using UnderscoreJS, the code would look very similar:
var filterdArr = _.filter(Array1, function(val) {return Array2.indexOf(val) != -1});
function removeDupes(a1, a2) {
var index = {}, result = [], i, l;
for (i=0, l=a2.length; i<l; i++) {
index['-' + a2[i]] = "";
}
for (i=0, l=a1.length; i<l; i++) {
if (index['-' + a1[i]] !== "") result.push(a1[i]);
}
return result;
}
The index object is for speedy look-up of values so we can test their existence quickly.
The '-' + is to migrate the fact that values could be things like toString that also exist as object properties. When prefixed with a letter that regular JavaScript identifiers cannot start with, every value will be safe for use as an object key.
Example:
removeDupes([1,2,3,4], [2,4,5]);
// -> [1,3]
removeDupes([2,4,5], [1,2,3,4]);
// -> [5]
Check this link: http://www.developersnippets.com/2008/10/30/remove-duplicates-from-array-using-javascript/. Concat your arrays with concat() and call uniqueArr().

Javascript: get all integer keys and all values in an Array?

Object.keys(obj) returns an Array of strings that are the keys of an object.
But what if the object is an array and I want the list of integer indexes that it has?
Is there a simple way to extract this without having to parseInt() them all?
Alternatively, is there a simple way to implement a sort of Object.values() to get an Array of the values (with normal Array integer keys) from an object?
You can loop the array for():
var arr = ["aaaa", "bbbb", "cccc"];
var iArr = [];
for(var i in arr)
{
iArr[i] = i;
alert(i+ " > " + arr[i]);
}
alert(iArr.length);
http://jsfiddle.net/Achilleterzo/kfLzD/
According to the final final final final draft of ES5, it seems that there is nothing like what you are looking for.
I think that all you can do is
var numericKeys = Object.keys(myObject).filter(function (key) {
return parseInt(key, 10).toString() === key;
});

Categories

Resources