When using the query builder in typeorm I do a select of a single column and I would like to get an array of values (In my particular case it would be an array of strings) but instead I get an array of objects where the key is the column name and the value is the row value.
For example the code:
this.createQueryBuilder('subscriptions')
.select('id')
.getRawMany()
Would return something like:
[{id:1},{id:2},{id:3}]
Instead of a simple array like [1,2,3]
Is there any way to obtain this array from the query? or the only way is to map the result of the query to extract the value?
Only option you have is map
const arrayResults = queryResults.map(r => r.id);
I am trying to push some values to an empty array that I am getting from an api call. When the values are console.logged, they appear like this:
POP: 7758
but when I push them to the array
array.push(item);
and console.log(array), they appear like this:
["7758"]
How can I get these values to be numbers or integers? I need to summarize the array once all the items are pushed there.
You might do array.push(+item)
You need to parse that string to number using parseInt():
var item = '7788';
var array = [];
array.push(parseInt(item));
console.log(array);
But if your string is also expected to have floating values then you need to use parseFloat():
var item = '7788.11';
var array = [];
array.push(parseFloat(item));
console.log(array);
So, it is always better to use parseFloat() as it works for both decimal/non-decimal numbers.
I have a Javascript Object in the format key:pair where the pair is an array containing 2 timestamp values. I would like to sort this object so that the elements with the lowest numbers (earliest times) are displayed first.
Here is an example of the object: {"21_2":[1409158800,1409160000],"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600]}
So in this case, I would want the final sorted object to read:
{"20_1":[1409148000,1409149200],"56_1":[1409149800,1409151600],"21_2":[1409158800,1409160000]}
Obviously the sort() function will come into play here for the arrays, but how do I access those values inside the object? Note the object key isn't actually an integer because of the underscore.
I have found this: Sort Complex Array of Arrays by value within but haven't been able to apply it to my situation. Any help would be greatly appreciated.
You could change the structure of your data like this:
var myArray = [{
"id" : "21_2" // id or whatever these are
"timeStamps" : [1409158800,1409160000]
}, {
"id" : "20_1"
"timeStamps" : [1409148000,1409149200]
}];
Then you could sort it by the regular array sort:
myArray.sort(function(a, b){
// however you want to compare them:
return a.timeStamps[0] - b.timeStamps[0];
});
I have a textbox in which a user its going to input a value which I want to take and do the following. I want to be able to separate each word and add something to the end of them. so if they put 123. I want to separate it and make it 1.jpg, 2,jpg 3.jpg
after they are separated i want to put it in an array to compare to another array and go from there.
Here is what I got so far
<input type="text" id="textfromuser" />
<script type = "text/javascript">
function validate(){
var lists = [];
var VAlidation = document.getElementById("textfromuser").value;
lists.push(VAlidation);
for(var i=0; i<lists.length; i++)
alert(lists[i]).split('.');
this part of the code was to show that the value in the textbox is split and placed in an array but its not working.. any ideas?
I think you are confusing arrays and strings, the value you obtain from the input is a string and you're afterwards adding it to the lists array and iterating over that array.
May be this is what you were looking for
HTML
<input type="text" id="textfromuser" />
Javascript
function validate(){
// empty array
var ar = [];
// obtain a string from the input "text" field, retrieved by the "id" attribute
var VAlidation = document.getElementById("textfromuser").value;
// split the string into a character array
var lists = VAlidation.split('');
// iterate over the character array
for(var i=0; i<lists.length; i++){
// create a string concatenating the array's element and '.jpg'
var str = lists[i]+'.jpg';
// add the string var to the array
ar.push(str);
}
return ar;
}
I created a jsfiddle to test it quickly if you want a try
http://jsfiddle.net/kpw23/2/
UPDATE
To compare arrays there are many ways to accomplish it. A simple way to achieve this would be to serialize the arrays and compare the serialized strings:
// having two arrays
var list = ['1.jpg','2.jpg','3.jpg'];
var list2 = ['1.jpg','2.jpg','3.jpg'];
// "Serialize" the arrays, the join() method
/// joins the elements of an array into a string, and returns the string
serlist = list.join();
serlist2 = list2.join();
// Compare both serialized arrays
if(serlist==serlist2){
alert("Arrays are equal");
}
else{
alert("Arrays are not equal");
}
This method will only work if the arrays are sorted the same way and contain exactly the same entries in the same array positions.
Your alerting the value of lists[i], not lists[i].split('.'). Try:
alert(lists[i].split('.'));
Is there any way efficiently to join JSON data? Suppose we have two JSON datasets:
{"COLORS":[[1,red],[2,yellow],[3,orange]]}
{"FRUITS":[[1,apple],[2,banana],[3,orange]]}
And I want to turn this into the following client side:
{"NEW_FRUITS":[[1,apple,red],[2,banana,yellow],[3,orange,orange]]}
Keep in mind there will be thousands of records here with much more complex data structures. jQuery and vanilla javascript are both fine. Also keep in mind that there may be colors without fruits and fruits without colors.
NOTE: For the sake of simplicity, let's say that the two datasets are both in the same order, but the second dataset may have gaps.
Alasql JavaScript SQL library does exactly what you need in one line:
<script src="alasql.min.js"></script>
<script>
var data = { COLORS: [[1,"red"],[2,"yellow"],[3,"orange"]],
FRUITS: [[1,"apple"],[2,"banana"],[3,"orange"]]};
data.NEW_FRUITS = alasql('SELECT MATRIX COLORS.[0], COLORS.[1], FRUITS.[1] AS [2] \
FROM ? AS COLORS JOIN ? AS FRUITS ON COLORS.[0] = FRUITS.[0]',
[data.COLORS, data.FRUITS]);
</script>
You can play with this example in jsFiddle.
This is a SQL expression, where:
SELECT - select operator
MATRIX - modifier, whci converts resultset from array of objects to array of arrays
COLORS.[0] - first column of COLORS array, etc.
FRUITS.1 AS 2 - the second column of array FRUITS will be stored as third column in resulting recordset
FROM ? AS COLORS - data array from parameters named COLORS in SQL statement
JOIN ? ON ... - join
[data.COLORS, data.FRUITS] - parameters with data arrays
The fact that there will be thousands of inputs and the keys are not necessarily ordered means your best bet (at least for large objects) is to sort by key first. For objects of size less than about 5 or so, a brute-force n^2 approach should suffice.
Then you can write out the result by walking through the two arrays in parallel, appending new "records" to your output as you go. This sort-then-merge idea is a relatively powerful one and is used frequently. If you do not want to sort first, you can add elements to a priority queue, merging as you go. The sort-then-merge approach is conceptually simpler to code perhaps; if performance matters you should do some profiling.
For colors-without-fruits and fruits-without-colors, I assume writing null for the missing value is sufficient. If the same key appears more than once in either color or fruit, you can either choose one arbitrarily, or throw an exception.
ADDENDUM I did a fiddle as well: http://jsfiddle.net/LuLMz/. It makes no assumptions on the order of the keys nor any assumptions on the relative lengths of the arrays. The only assumptions are the names of the fields and the fact that each subarray has two elements.
There is not a direct way, but you can write logic to get a combined object like this. Since "apple, red, banana...." are all strings, they should be wrapped in a single or double quote.
If you can match the COLORS and FRUITS config array by adding null values for missing items then you can use this approach.
Working demo
var colors = {"COLORS":[[1,'red'],[2,'yellow'],[3,'orange']]}
var fruits = {"FRUITS":[[1,'apple'],[2,'banana'],[3,'orange']]}
var newFruits = {"NEW_FRUITS": [] }
//Just to make sure both arrays are the same size, otherwise the logic will break
if(colors.COLORS.length == fruits.FRUITS.length){
var temp;
$.each(fruits.FRUITS, function(i){
temp = this;
temp.push(colors.COLORS[i][2]);
newFruits.NEW_FRUITS.push(temp);
});
}
Alternatively, if you can create colors and fruits configs as an array of objects, instead of an array of arrays, you can try this solution. The sequence of the elements is irrelevant here, but the array size should still match.
Working demo
var colors = {"COLORS":[ {"1": 'red'}, { "2": 'yellow'}, {"3":'orange'}]}
var fruits = {"FRUITS":[ {"1":'apple'}, { "2": 'banana'}, {"3":'orange'}]}
var newFruits = {"NEW_FRUITS": [] }
if(colors.COLORS.length == fruits.FRUITS.length){
var temp, first;
$.each(fruits.FRUITS, function(i){
for(first in this)break;
temp = {};
temp[first] = [];
temp[first].push(this[first]);
temp[first].push(colors.COLORS[i][first]);
newFruits.NEW_FRUITS.push(temp);
});
}