Pushing a string value as an integers - javascript

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.

Related

JS: Iterate over an array of objects to update object

I am trying to iterate over an array of array objects to de-dupe and sort the data within each. The function onlyUnique returns unique values in an array. The problem is, it doesn't work as intended.
arr_lists = [arr_1, arr_2, arr_3, arr_4, arr_5, ...]
for (var list_obj of arr_lists) {
list_obj = list_obj.join().split(',').filter(onlyUnique);
list_obj.sort();
Logger.log(list_obj);
}
The logger results show true (i.e. they are what I am looking for), but the original array is unchanged, although I think it should have been updated.
I've tried assigning the filtered array to a new array... nope.
I know that I could add a thousand lines of code to achieve the results, but that seems silly.
I suspect it's something obvious.
You can simply achieve it by using Set data structure to remove the duplicates and Array.sort() compare function to sort the elements in an array.
Live Demo :
const arr_lists = [[2,3,5,6], [7,2,5,3,3], [1,5,3], [4,7,4,7,3], [1,2,3]];
arr_lists.forEach((arr, index) => {
arr_lists[index] = [...new Set(arr)].sort((a, b) => a -b);
})
console.log(arr_lists);

Sort the array of database object-id

I have a array of mongodb object-id and i want to sort them in such a way that similar IDs are next to each other
example :
Input :
var array = ["507f191e810c19729de860ea","00000020f51bb4362eee2a4d",” 507f191e810c19729de860ea”]
Output :
var array = ["507f191e810c19729de860ea","507f191e810c19729de860ea","00000020f51bb4362eee2a4d"]
Simply sorting the input array would result in the same input array being sorted in natural order (converting the input to a string, if needed, and comparing the elements UTF-16 code units):
array.sort();
In case you would want the reverse order, you can reverse the array:
array.sort().reverse();

How to convert Associative array to a simple string array of values in javascript

So I want to convert this array retrieved from a database to just an array of string values:
Array:[{"userid":"c"},{"userid":"d"}]
Expected results:["c","d"]
you can use the map function
result = myArray.map(function(item){ return item.userid; })
If you need this conversions on javascript side, you should keep in mind, that if there would be a lot of items, the performance might be rather bad. May be it would be better to change logick of gathering the first array.
For conversion you could try this:
Data = [{"userid":"c"},{"userid":"d"}];
arr = [];
for(i in Data){
arr.push(Data[i].userid);
}
console.log(arr);
A simpler way would be
const results = myArray.map(item => item.userId);

How can I push a null value into the start of an array?

I have this code that fetches data and puts it into an array:
this.$httpGetTest(this.test.testId)
.success(function (data: ITestQuestion[]) {
self.test.qs = data;
});
It works and populates the array starting with self.test.qs[0].
However many times my code references this array (which contains a list of questions 1...x)
I must always remember to subract 1 from the question number and so my code does not look clear. Is there a way that I could place an entry ahead of all the others in the array so that:
self.test.qs[0] is null
self.test.qs[1] references the first real data for question number 1.
Ideally I would like to do this by putting something after the self.test.qs = and before data.
Push values at start of array via unshift
self.test.qs.unshift(null);
You need to use Splice(), It works like:
The splice() method changes the content of an array, adding new elements while removing old elements.
so try:
self.test.qs.splice(0, 0, null);
Here mid argument 0 is to set no elements to remove from array so it will insert null at zero and move all other elements.
Here is demo:
var arr = [];
arr[0] = "Hello";
arr[1] = "Friend";
alert(arr.join());
arr.splice(1,0,"my");
alert(arr.join());
You can start off with an array with a null value in it, then concat the questions array to it.
var arr = [null];
arr = arr.concat(data);
You could do something like:
x = [null].concat([1, 2, 3]);
Though there isn't anything wrong with doing something like:
x[index-1]
I'd prefer it to be honest, otherwise someone might assume that the index value returned is 0 based.

separate values of a textbox and place it on an array in javascript

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('.'));

Categories