How to parse through array of objects and convert string numbers to integers - javascript-objects

Working with JS. I have an array of objects. Here is a sample below. You can see that all the values are strings. However, I need to convert the lft and rgt values into integers so that I can compare these values against other values held in a different array. Keeping them as strings and comparing gives me erroneous results.
nodesWithchildren
:Array[1]
0:Object
category_id:"8"
created_at:"2016-11-04 14:14:28"
lft:"17"
name:"Felt Materials"
rgt:"22"
updated_at:"-0001-11-30 0:00:00"
__proto__:Object
I have searched through Stackoverflow and found various suggestions. All of them use for loops with parseInt which is great BUT they assume that the values either are all string numbers AND they assume that the values are held in a simple array. Not an array of objects.
I tried using this, but this does NOT work. Probably because parseint does not like it. IN fact it crashes the page:
var nodesWithchildrenParsed =[];
for(var i=0; nodesWithchildren.length;i++){
nodesWithchildrenParsed[i] = parseInt(nodesWithchildren[i]);}
My first step is converting these values. Once I have the lft and rgt converted to integers I will run another function where I will say something like, "if lft is greater than X and rgt is less than Y then give me the name "felt materials".
Tks !

The easy way to convert a string to a number without using parseint() is to simply divide the string by the integer 1. In my case this was a perfect solution as I did not have to deal with the fact that the strings were in an array of objects, other that doing this:
var childNodes=[];
for(i=0; i < selectedArray.length; i++){
if((selectedArray[i].lft /1 ) > (nodesWithchildren[0].lft /1) && (selectedArray[i].rgt/ 1) < (nodesWithchildren[0].rgt/1)) {
childNodes += selectedArray[i].name;
}
}
JS will convert the string before undertaking any operations on it. Cody's Example:
console.log( ('2'/1) > ('10'/1) );
Credit goes to Cody and his answer here:
Cody's answer

Related

How do I create a string of array combinations given a list of "source code" strings?

Basically, I’m given a list of strings such as:
["structA.structB.myArr[6].myVar",
"structB.myArr1[4].myArr2[2].myVar",
"structC.myArr1[3][4].myVar",
"structA.myArr1[4]",
"structA.myVar"]
These strings are describing variables/arrays from multiple structs. The integers in the arrays describe the size each array. Given a string has a/multiple arrays (1d or 2d), I want to generate a list of strings which go through each index combination in the array for that string. I thought of using for loops but issue is I don’t know how many arrays are in a given string before running the script. So I couldn’t do something like
for i in range (0, idx1):
for j in range (0, idx2):
for k in range (0, idx3):
arr.append(“structA.myArr1[%i][%i].myArr[%i]” %(idx1,idx2,idx3))
but the issue is that I don’t know how I can create multiple/dynamic for loops based on how many indexes and how I could create a dynamic append statement that changes per each string from the original list since each string will have a different number of indexes and the arrays will be in different locations of the string.
I was able to write a regex to find all the index for each string in my list of strings:
indexArr = re.findall('\[(.*?)\]', myString)
//after looping, indexArr = [['6'],['4','2'],['3','4'],['4']]
however I'm really stuck on how to achieve the "dynamic for loops" or use recursion for this. I want to get my ending list of strings to look like:
[
["structA.structB.myArr[0].myVar",
"structA.structB.myArr[1].myVar",
...
"structA.structB.myArr[5].myVar”],
[“structB.myArr1[0].myArr2[0].myVar",
"structB.myArr1[0].myArr2[1].myVar",
"structB.myArr1[1].myArr2[0].myVar",
…
"structB.myArr1[3].myArr2[1].myVar”],
[“structC.myArr1[0][0].myVar",
"structC.myArr1[0][1].myVar",
…
"structC.myArr1[2][3].myVar”],
[“structA.myArr1[0]”,
…
"structA.myArr1[3]”],
[“structA.myVar”] //this will only contain 1 string since there were no arrays
]
I am really stuck on this, any help is appreciated. Thank you so much.
The key is to use itertools.product to generate all possible combinations of a set of ranges and substitute them as array indices of an appropriately constructed string template.
import itertools
import re
def expand(code):
p = re.compile('\[(.*?)\]')
ranges = [range(int(s)) for s in p.findall(code)]
template = p.sub("[{}]", code)
result = [template.format(*s) for s in itertools.product(*ranges)]
return result
The result of expand("structA.structB.myArr[6].myVar") is
['structA.structB.myArr[0].myVar',
'structA.structB.myArr[1].myVar',
'structA.structB.myArr[2].myVar',
'structA.structB.myArr[3].myVar',
'structA.structB.myArr[4].myVar',
'structA.structB.myArr[5].myVar']
and expand("structB.myArr1[4].myArr2[2].myVar") is
['structB.myArr1[0].myArr2[0].myVar',
'structB.myArr1[0].myArr2[1].myVar',
'structB.myArr1[1].myArr2[0].myVar',
'structB.myArr1[1].myArr2[1].myVar',
'structB.myArr1[2].myArr2[0].myVar',
'structB.myArr1[2].myArr2[1].myVar',
'structB.myArr1[3].myArr2[0].myVar',
'structB.myArr1[3].myArr2[1].myVar']
and the corner case expand("structA.myVar") naturally works to produce
['structA.myVar']

VBA compare Abs() values not working

I have two arrays of data where I want to compare every element in both arrays and put the biggest absolute value in an new array. See code below:
If Abs(DataArray1(i)) < Abs(DataArray2(i)) Then
NewDataArray(i) = DataArray2(i)
Else
NewDataArray(i) = DataMinArray(i)
End If
The probem is that some of the values are decimals and if I compare for example -1.02 and 1.0100 then normaly -1.02 has bigger abs value. In my case my program returns 1.0100 and it happens to all values are not the same length. The longer one is always returned. How could that happen and what is wrong?
are the arrays of String type? Otherwise i couldn't explain why values like 1.0100 even exist. That value should automatically be shown as 1.01
If you are working with Strings then try to convert the values to floats. This could work: Abs(CDbl(DataArray1(i))) < Abs(CDbl(DataArray2(i)))

matlab cell contents , how to tell what they are?

I have a cell array, c, filled with hexadecimal data and when I view the cell contents by typing c at the matlab prompt, it shows me contents enclosed between ticks, i.e., '0x0009'. But, one element is enclosed in brackets and looks like [650345]. How can I convert the [ ] data to ' ' data? When I do iscellstr on this particular element, matlab returns 0. iscellstr returns 1 for all other elements of c.
I'm reading this data into matlab from excel and I fear that excel 'helped' me by converting one hex value to scientific notation. I can't, as far as I've found, change what excel did. I think the true value is lost and unrecoverable. But I need to convert this one outstanding value, even if incorrect, to be like the other cell values so that I can carry on with my processing. Any suggestions?
If you know the index of wrong value and it's true value, you just do:
c(idx) = {'0x0009'};
I think this does what you want:
ind = cellfun(#isnumeric, c); %// find numeric cells
c(ind) = cellfun(#(s) ['0x' dec2hex(s)], c(ind), 'uniformout', 0); %// convert to
%// hex string and prepend '0x'
Example: input
c = {'0x0009', 650345};
produces the output
c =
'0x0009' '0x9EC69'

how to get array of properties from array of objects in matlab

I am using an array of objects in my program, and each object has several attributes. I want to be able to extract separate arrays from this array of objects, one array for each attribute.
here is a snippet of the relevant code:
dailyDataMatrix(m,n)=dailyData('',''); %creates an mxn array of dailyData objects
for i=1:m
for j=1:n
dailyDataMatrix(i,j)=dailyData(datainput1, datainput2)%dailyData constructor, sets attributes
end
end
dailyDataMatrix.attribute
But when I try to access a certain attribute as in the code above, say of type string, I get a strange result. Instead of getting an array of strings, I get something else. When I try to print it, rather than printing an array, it prints a series of individual values
ans = 'string1'
ans = 'string2'
...
When I try to call
size(dailyDataMatrix.attribute)
className = class(dailyDataMatrix.attribute)
I get
"error using size: too many input arguments" and
"error using class: The CLASS function must be called from a class constructor."
However, when I write this as
thing=dailyDataMatrix.attribute
className = class(thing)
size(thing)
I get the response
classname = 'double' and size = 1x1.
Why is this not returning an array the same size as dailyDataMatrix? And an aside question is why the two different ways of writing the code above give different results? and how can I get the result that I want?
Thanks,
Paul
You can capture all the outputs using a cell array or using square brackets if the types are same. For regular array when all values are of same type use,
thing=[dailyDataMatrix.attribute];
If the types are different you can use
thing = cell(1,N); % N is the number of elements in dailyDataMatrix
[thing{:}] = dailyDataMatrix.attribute;

Create new array from integer elements of another array? MATLAB

I have created an array tP which contains a mix of integer and non-integer elements. I want to create a new array of the integer element.
The result I would like is in the same form as is returned for, for example:
tP2=find(tP>300);
That is, a list of the element numbers which contain integer values, not a list of the integers themselves.
From this I will then select the desired elements like so:
tP3=tP(tP2);
To do this for integers, what I currently have is:
tP2=find(isinteger(int16(tP)));
But instead of a list of element numbers, I just get tP2=1 returned.
Why does isinteger not work in this case and how can I achieve my required result? Thanks.
use round
tp2 = find( tP == round(tP) );
As Shai says, comparison to round is an effective way to detect integers.
Next, unless you need the list of matches for something else, you don't need find. Just the comparison will create a mask array, and masks can be used for subscripting.
tP3 = tP(tP == round(tP));
Getting rid of tP2 and the call to find should save time and memory.

Resources