I'm trying to parse out a single value from a URL String with three varaibles, and I am currently using the code:
var hash_array = location.hash.substring(1).split('&');
var hash_key_val = new Array(hash_array.length);
for (var i = 0; i < hash_array.length; i++) {
hash_key_val[i] = hash_array[i].split('=');
var array = hash_key_val[i];
console.log(array);
}
This code works to parse out the hash, but it creates separate arrays for each item and value like so:
["object1", "value1"]
["object2", "value2"]
["object3", "value3"]
By altering the array to var x = JSON.stringify(array[1]);
I can get the value which is all I need, but I only need the first value, while this code still returns:
"value1"
"value2"
"value3"
How can I alter the code so that the function only outputs value1?
Thanks!
Change the 1 for 0; Arrays start at zero index. Also I am not sure if you are aware that you are looping over the values as you are printing them out.
var arr = [
["object1", "value1"],
["object2", "value2"],
["object3", "value3"]
];
console.log(arr[0][1]);
As Arrow mentioned you need to change the index at which you access array from 1 to 0.
Additionally, why not use map:
var keys = hash_array.map(function(param){
return JSON.stringify(param.split('=')[0]);
}
with keys being ["object1", "object2", "object3"]
Related
I am trying to get unique values from two arrays which looks like that:
array[{A,B,C},{C,D,E},{1,3,2},....]
both looks the same.
I tried to add them using concat and the get unique values from looping.
So I ended up with this:
function uniqueValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = ss.getSheetByName("arr1");
const array1 = srcSheet.getRange(1, 1, srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
var srcSheet1 = ss.getSheetByName("arr2");
const array2 = srcSheet1.getRange(1, 1, srcSheet1.getLastRow(), srcSheet1.getLastColumn()).getValues();
var dodaj = array1.concat(array2);
for (var i=0; i<dodaj.length; i++) {
var listI = dodaj[i];
loopJ: for (var j=0; j<dodaj.length; j++) {
var listJ = dodaj[j];
if (listI === listJ) continue;
for (var k=listJ.length; k>=0; k--) {
if (listJ[k] !== listI[k]) continue loopJ;
}
dodaj.splice(j, 1);
}
}
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, 3).setValues(dodaj);
//Logger.log(dodaj);
}
It was working well when array looked like this array[{A,B},{C,D}] but with three elements it started to return duplicates as well... I have no idea what can be wrong.
If I understand you correctly, you want to retrieve the unique rows from the values in arr1 and arr2. That is to say, you want to remove duplicate inner arrays from dodaj.
After using concat to merge the two arrays, you could do the following:
Use JSON.stringify() to transform each inner array to a string, in order to compare them without iterating through them.
Use the Set constructor and the spread syntax in order to remove the duplicate strings (see this answer).
Transform the strings back to arrays with JSON.parse().
Code snippet:
var dodaj = array1.concat(array2);
dodaj = [...new Set(dodaj.map(JSON.stringify))].map(JSON.parse);
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, dodaj[0].length).setValues(dodaj);
So the issues that I am currently having is a string manipulation logic issue. My goal is to store the names of JSON objects in a string array. So it will be easier to access the data later on. But the current issue that I am running into is that the output is nothing that I want or understand of how it is getting it. Currently I am looking for the quotes between the object names and returning it to a string using str.substring, and storing it in an index of newArr. The output equals in 4th code snippet. I have also tried putting an underscore before and after the object name in the JSON object, then searching for the underscore. From my testing this will only work with the first name, which will return "foo" in index 0, while the rest of the indexes equal to '"_'. I know there is something wrong with my logic in the function, but I can not pinpoint what it is. Any help would be appreciated
This is the function that is being ran.
exports.jsonObjectToArray = function (objectToTurn){
var oldArr = JSON.stringify(objectToTurn).split(","),
firstIndex,
secondIndex,
newArr = [];
for(let i = 0; i < oldArr.length; i ++){
firstIndex = oldArr[i].indexOf("\"");
secondIndex = oldArr[i].indexOf(firstIndex, "\"");
newArr[i] = oldArr[i].substring(firstIndex, secondIndex);
}
return newArr;
}
When the function is ran oldArr will equal to this value.
[ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
And my goal is to return this. Which will be stored in newArr.
[
"foo",
"bar",
"Mar",
"Car"
]
But after the function runs this is what I get returned.
[
'{"',
'bar":"0',
'Mar":"0',
'Car":"0'
]
To get the keys from an object, simply use Object.keys().
Quick example:
var obj = {
foo: '1',
bar: '2',
car: '3'
};
console.log(Object.keys(obj)); // ==> (3) ["foo", "bar", "car"]
let arr = [ '{"foo":"',
'"bar":"0"',
'"Mar":"0"',
'"Car":"0"}'
]
let arr1 = arr.map(el => el.split('"')[1])
I have been searching A LOT to find a simple way to loop through an array (I haven't used javascript much) and I just can't seem to make sense of the examples I've seen.
I also want to retrieve data from an array...
The following example I can understand:
https://www.w3schools.com/js/js_loop_for.asp
But it's just not useful for the use case I want it for.
Say I have an array that looks like this:
array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
Question 1: How can I access the first object in that array, i.e. where the 'key' = 1?
Question 2: How can I then loop through the "values" from this object?
e.g. In Python I would do something like:
get_first_object = array1[0]
for value in array1['values']:
print value
How can I do this kind of coding in javascript?
Edit
I didn't mention this properly
My "array1" is coming from a Python view and so the output of this is different to a standard JS array (see output of console.log below):
["[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values':["two", "2"]}]"]
so when I do var object = array1[0] I get the following output:
[{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}]
It doesn't seem to be getting the first object but rather seeing the whole thing as one object.
Also
I require to get this dynamically - so I can't actually hard code "array1[0]" or "array1[1]" - How can I do this?
How I am defining the array
var array1 = ["{{ my_array_1|safe }}"];
Edit 2
The way I wish to get the object from the array is like so:
var selected_id = 1;
var selected_object = array[key=selected_id];
Let's assume that your array is this:
var array = [{'key': 1, 'values': ["one", "1"]}, {'key': 2, 'values': ["two", "2"]}];
This is an array which contains javascript objects, each with 2 properties, 'key', whose corresponding value is an integer and 'values' whose corresponding value is an array of data. If I understand this correctly, you want, given an integer input_id, to access the aforementioned array of data.
function access_data (id) {
for(let obj of array){
if(obj['key'] == id){
return obj['values'];
}
}
}
If you are familiar with python you probably recognize the for .... of syntax, since it's basically the same as python's for .... in. The above code assumes that your array is a global variable called array. Calling the function with an integer argument loops through every object your array contains, checks if its 'key' property matches the given id, and if it does, the corresponding array of data is returned.
More details on for ... of loops here
This self explanatory code should rectify your doubts
var array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}];
// First Object
var firstObject = array1[0];
console.log("First object", firstObject);
// Accessing key property of first object
var keyOfFirstObj = firstObject.key;
console.log("Key", keyOfFirstObj);
// Iterating through all the values of first object
Object.values(firstObject).forEach(
el => console.log("Value -- ", el)
)
You can hardcode it: array1[0].key // 1
Use forEach to loop over:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.forEach(arrItem => console.log(arrItem))
Or map over it if you intend to change datas as #str said below:
const array1 = [{'key':1, 'values':["one", "1"]}, {'key':2, 'values':["two", "2"]}]
array1.map(arrayItem => console.log(arrayItem);
On mapvs forEach:
https://codeburst.io/javascript-map-vs-foreach-f38111822c0f
There are a few ways to do this, the basic for loop and the for..of loop
for
for (let i = 0; i < array1.length; i++) {
console.log(array1[i])
}
for..of
for (const val of array1) {
console.log(val)
}
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of
if you want to select an object that has a key property of "1", you could loop through the array using the methods above, returung when that condition is true, or you could use Array#filter
const filtered = array1.filter(item => item['key'] === 1) //=> returns a new array
const myObj = filtered[0]
If you want a similar syntax to Python, you Coups use the for...in loop:
let get_first_object = array1[0];
for (let index in array1['values']){
console.log(array1['values'][index]);
}
Edit:
As for your edit, you need 2 loops
let objectArray= array1[0];
if(objectArray){
for(let outerIndex in objectArray){
for(let innerIndex in objectArray[outerIndex]['values']){
console.log(objectArray[outerIndex]['values'][innerIndex];
}
}
}
Edit:
let objectArray= array1[0];
if(objectArray){
let valuesObject=objectArray.filter(f=>f.key===selectedId);
for(let innerIndex in valuesObject['values']){
console.log(valuesObject ['values'][innerIndex];
}
}
}
I have an array that looks like this:
var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];
I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.
var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
//add to my newArray like this : ['title1','description1'],['title3','description3']
?
}
How can I do it?
Try like below,
var newArray = [];
for (var i = 0; i < locationsArray.length; i++) {
if (parseInt(locationsArray[i][2], 10) > 10) {
newArray.push([locationsArray[i][0], locationsArray[i][1]]);
}
}
DEMO: http://jsfiddle.net/cT6NV/
It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.
For instance, if I retrieve locationsArray[0] I get ['title1','description1','12']. If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1'.
Completing your example:
var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}
throw that in a loop and you're good to go.
It's an array of arrays of strings.
Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).
So, if we take the following example :
var myArray = ["string", "string2", ["string3-1", "string3-2"]];
The values would be as such :
myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"
There can be as many levels of depth as your RAM can handle.
locationsArray is an array of arrays. The first [] operator indexes into the main array (e.g. locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (e.g. locationsArray[0][1] = 'description1').
Your newArray looks like it needs to be the same thing.
It's an array of array.
var newArray = [];
var locationsArray = [
['title1','description1','12'],
['title2','description2','7'],
['title3','description3','57']
];
for(i = 0; i < locationsArray.length; i++) {
if (locationsArray[i][2] > 10) {
newArray .push([locationsArray[i][0], locationsArray[i][1]]);
}
}
console.log(newArray );
Is there a better way to create a two-dimensional array in javascript than this?
var divcookies = new Array();
divcookies[0] = new Array(2);
divcookies[0][0] = name;
divcookies[0][1] = value;
This results in a two dimensional array with bad data added in the middle of it. I expect an array like this.
(name1, value1, name2, value2, name3, value3)
Instead I get this.
(name1, value2, ,name2, value2, name3, value3)
I don't really know when that extra bad data is added because if I alert during the loop that fills the array it only seems to loop through 3 times to put the three pairs of values expected.
So I am looking for a different way to get the two dimensional array.
function get_cookies_array() {
var divcookies = new Array();
if (document.cookie && document.cookie != '') {
var split = document.cookie.split(';');
for (var i = 0; i < split.length; i++) {
var name_value = split[i].split("=");
name_value[0] = name_value[0].replace(/^ /, '');
if ( name_value[0].search("compage") != -1 ) {
alert (divname+" "+ divarray);
divcookies[i] = new Array(2);
divcookies[i][0] = decodeURIComponent(name_value[0]);
divcookies[i][1] = decodeURIComponent(name_value[1]);
}
}
}
alert (divcookies);
return divcookies;
}
jsBin http://jsbin.com/iwuqab
The recommended method for creating arrays in JS is to NOT use the 'new' method. Instead, do:
var divcookies = [];
divcookies[0] = [];
divcookies[0][0] = name;
divcookies[0][1] = value;
This notation frees you up from having to specify element numbers in advance. Once a variable's been initialized as an array, you can set any index you want. The downside (regardless of which notation you use) is that you have to initialize every sub-array as well.
Your 2-dimensional array is set up correctly (well, [] is preferred instead of new Array()). The actual problem is only with the display of your array using alert(divcookies). Here, divcookies is converted to a string using the predefined method toString(). This method creates a list of comma-separated array elements, from the first element to the last element. If some elements in between are not set, an empty string is output. In your case, you are not assigning to those indexes i of divcookies for which name_value[0].search("compage") == -1. These are the gaps ,, in the alerted list.