How can I rewrite python code to javascript? - javascript

The code in python is:
def trimTree(tree):
p=tree[1]
if type(p) == type(""): return p
else :
return(trimTree(p[0]),trimTree(p[1]))
where tree is:
[
13,
[ 6, [ 3, [Object], [Object] ], [ 3, 'a' ] ],
[ 7, [ 3, 'b' ], [ 4, [Object], [Object] ] ]
]
when I convert I got error:
TypeError: Cannot read property '0' of undefined
What should I do?

With a proper data structure, which means any node has only a length of two elements, you get a list of values in breaths first order (the result is here a string).
function trimTree(tree) {
var p = tree[1];
return typeof p === 'string'
? p
: trimTree(p[0]) + trimTree(p[1]);
}
var data = [
13,
[
[6,
[
[3,
[
[1, 'X'],
[2, 'Y']
]
],
[3, 'a']
]
],
[7,
[
[3, 'b'],
[4,
[
[2, 'Z'],
[2, 'Q']
]
]
]
]
]
];
console.log(trimTree(data));

Related

Looping and splitting Object

how to loop on object and split it by ":" into separate one
{
labs: [1,2,":",3,4],
level: [1,2,":",3,4]
}
Expected Output:
{
labs: [1,2],
level: [1,2]
}
{
labs: [3,4],
level : [3,4]
}
You can use itertools.groupby from the standard library to group the numbers that are not ":". With that you can use zip to pair off the groups.
from itertools import groupby
d = {
"labs": [1,2,":",3,4],
"level": [10,20,":",30,40]
}
groups = [[(k, list(g)) for b, g in groupby(v, key=lambda n:n != ':') if b]
for k, v in d.items()
]
list(map(dict, zip(*groups)))
# [
# {'labs': [1, 2], 'level': [10, 20]},
# {'labs': [3, 4], 'level': [30, 40]}
# ]
This should work with arbitrary data. For example with input like:
d = {
"labs": [1,2,":",3,4,":", 5, 6],
"level": [10,20,":",30,40,":",50, 60],
"others":[-1,-2,":",-3,-4,":",-5,-6]
}
You will get:
[{'labs': [1, 2], 'level': [10, 20], 'others': [-1, -2]},
{'labs': [3, 4], 'level': [30, 40], 'others': [-3, -4]},
{'labs': [5, 6], 'level': [50, 60], 'others': [-5, -6]}
]
But it does expect the lists to be the same length because the way zip() works. If that's not a good assumption you will need to decide what to do with uneven lists. In that case itertools.zip_longest() will probably be helpful.
Use javaScript to resolve this problem, maybe the code is not the best
const obj = {
labs: [1,2,":",3,4,":",5,6],
level: [1,2,":",3,4,":",7,8],
others: [1,2,":",3,4,":",9,10]
}
const format = (obj = {}, result = []) => {
const keys = Object.keys(obj);
for ( key of keys) {
const itemValues = obj[key].toString().split(':');
let tempRes = {}
itemValues.map((itemValue, index) => {
Object.assign(tempRes, {
[`${keys[index]}`]: itemValue.replace(/^(,)+|(,)+$/g, '').split(',').map(Number)// you can format value here
})
})
result.push(tempRes);
}
return result;
}
console.log(format(obj))
You will get
[
{ labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 5, 6 ] },
{ labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 7, 8 ] },
{ labs: [ 1, 2 ], level: [ 3, 4 ], others: [ 9, 10 ] }
]

Convert Array groups into object

I have an array. And i want to convert them into a group of objects.
below is my array
[ null,
[ 5, 6 ],
[ 7, 8 ],
[ 9, 10 ],
[ 13, 14 ] ]
Then i tried them to convert into object by pairs but what i had was this:
{ '0': null,
'1': [ 5, 6 ],
'2': [ 7, 8 ],
'3': [ 9, 10 ],
'4': [ 13, 14 ] }
What i'm trying to achieve is something like below:
{
"0": 5,
"1": 6,
},
{
"0": 7,
"1": 8,
},
{
"0": 9,
"1": 10,
},
{
"0": 13,
"1": 14,
},
thank you for those who will help
You could filter falsy values and map objects where you have assigned the array.
var array = [null, [5, 6], [7, 8], [9, 10], [13, 14]],
result = array
.filter(Boolean)
.map(a => Object.assign({}, a));
console.log(result);
Wrapped in a function
function getObjects(array) {
return array
.filter(Boolean)
.map(a => Object.assign({}, a));
}
console.log(getObjects([null, [5, 6], [7, 8], [9, 10], [13, 14]]));
You should have a condition that skip the null value in the array:
function changeArray(arr){
var res = [];
arr.forEach((item)=>{
let obj = {};
if(item){
item.forEach((val, index)=>{
obj[index] = val;
});
res.push(obj);
}
});
return res;
}
var arr1 = [ null,
[ 5, 6 ],
[ 7, 8 ],
[ 9, 10 ],
[ 13, 14 ] ];
console.log(changeArray(arr1));
var arr2 = [ null,
[ 5, 6, 7 ],
[ 7, 8, 9 ]];
console.log(changeArray(arr2));

Numeric sort on an array with javascript

I have this array :
[ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ]
and I would like to have :
[ [ 11, 'g' ], [ 9, 'e' ], [ 9, 'h' ], [ 3, 'i' ], [ 2, 'b' ], [ 1, 'a' ], [ 1, 'd' ], [ 1, 'f' ] ]
How can I do that with javascript please ?
I tried sort(), I also tried with sort(compare) with :
function compare(x, y) {
return x - y;
}
You can use .sort() with Array Destructuring like this:
function compare([a], [b]) {
return b - a;
}
Demo:
let a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];
a.sort(compare);
function compare([a], [b]) {
return b - a;
}
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0; }
In case first elements match, you can sort based on 2nd element as well:
function compare([a, c], [b, d]) {
return (b - a) || c.localeCompare(d)
}
Demo:
let a = [ [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ], [ 1, 'a' ] ];
a.sort(compare);
function compare([a, c], [b, d]) {
return (b - a) || c.localeCompare(d);
}
console.log(a);
.as-console-wrapper { max-height: 100% !important; top: 0 }
You need to compare the first element in the nested array since you want to sort based on that number.
function compare(x, y) {
return y[0] - x[0];
}
var data = [
[1, 'a'],
[2, 'b'],
[1, 'd'],
[9, 'e'],
[1, 'f'],
[11, 'g'],
[9, 'h'],
[3, 'i']
];
function compare(x, y) {
return y[0] - x[0];
}
data.sort(compare);
console.log(data);
In case you want to sort based on second element(secondary sorting in case the first element is same) then use String#localeCompare method for comparing.
function compare(x, y) {
return y[0] - x[0] || x[1].localeCompare(y[0]);
}
var data = [
[2, 'b'],
[1, 'd'],
[9, 'e'],
[1, 'f'],
[1, 'a'],
[11, 'g'],
[9, 'h'],
[3, 'i']
];
function compare(x, y) {
return (y[0] - x[0]) || x[1].localeCompare(y[1]);
}
data.sort(compare);
console.log(data);
Compare the elements based on their first element, which is the number.
var a = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];
a = a.sort((a,b) => {
return b[0] - a[0]
});
console.log(a)
Use sort to compare first element and if first element is same then compare the second element.
arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) )
Demo
var arr = [ [ 1, 'a' ], [ 2, 'b' ], [ 1, 'd' ], [ 9, 'e' ], [ 1, 'f' ], [ 11, 'g' ], [ 9, 'h' ], [ 3, 'i' ] ];
arr.sort( (a,b) => (b[0] - a[0]) || (b[1] - a[1]) );
console.log(arr);

find and merge duplicate match with array in javascript

Following is an array of product which has been find and process on contact data and creates the possible array of merge occurrences.
In the following arrProduct, I would like to filter duplicate array and merge with existing array and finally create a unique array product called arrFinalProduct.
Array product
arrProduct =
[
[ 0 ],
[ 1, 2 ],
[ 2 ],
[ 3 ],
[ 4, 5, 6, 10 ],
[ 5, 6, 7, 11 ],
[ 6 ],
[ 7, 11 ],
[ 8 ],
[ 9 ],
[ 10 ],
[ 11 ],
[ 12 ],
[ 13, 14 ],
[ 14 ]
]
Final product
arrFinalProduct =
[
[ 0 ],
[ 1, 2 ],
[ 3 ],
[ 4, 5, 6, 7, 10, 11 ],
[ 8 ],
[ 9 ],
[ 12 ],
[ 13, 14 ]
]
arrProduct is the product array and arrFinalProduct is the final product array. The basic logic is that we require merging array, if any occurrences match found from an array.
Let's say value 0 is not found in any index in arrProduct so it does not merge and push into arrFinalProduct,
arrProduct value 2 is found on 1st and 2nd index so it may merge with 1st index and become [1,2] and delete 3rd index of [2].
arrProduct index 5 have two common value 5 and 6 and it also in index 6 so it may merge into 1 and become "4,5,6,7" and so on...
This process is going to process data recursively until I found unique value from an array. So it probably merges array horizontally.
Hope reader may get an enough idea.
Basically you could search for exisitent items in the result set and join the arrays with same items.
The order of items is the same as the appearance.
var array = [[0], [1, 2], [2], [3], [4, 5, 6, 10], [5, 6, 7, 11], [6], [7, 11], [8], [9], [10], [11], [12], [13, 14], [14]],
result = array.reduce(function (r, a) {
r.some(function (b, i, bb) {
if (a.some(c => b.includes(c))) {
bb[i] = [...new Set(b.concat(a))];
return true;
}
}) || r.push(a);
return r;
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

javascript: Trying to flatten array only one level

I am trying to write a function to flatten an array. I have part of the function working and I need help in the other half.
flatten: function(anyArray, singleLevel) {
if (singleLevel == true) {
flatArray = Array.prototype.concat.apply([], anyArray);
return flatArray;
}
flatArray = Array.prototype.concat.apply([], anyArray);
if (flatArray.length != anyArray.length) {
flatArray = someObject.array.flatten(flatArray);
}
return flatArray;
}
if I type
.flatten([[[1],[1,2,3,[4,5],4],[2,3]]], true);
I want it to flatten only one level:
[[1],[1,2,3,[4,5],4],[2,3]]
Modern JavaScript allows us to handle this very easily using a variety of techniques
Using Array.prototype.flat -
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
arr.flat(1) // 1 is default depth
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
Using Array.prototype.flatMap -
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
arr.flatMap(x => x)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
Using a spread argument to Array.prototype.concat
const arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
const flatArr =
[].concat(...arr)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
Older version of JavaScript (ECMAScript 5 and below) can use techniques like Function.prototype.apply -
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
Array.prototype.concat.apply([], arr)
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
Using Array.prototype.reduce -
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
arr.reduce((r, a) => r.concat(a), [])
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
Using a primitive for loop -
var arr =
[ [ 1 ], [ 2, 3, [ 4, 5, [ 6 ] ] ], [ 7, [ 8, 9 ] ] ]
var flatArr =
[]
for (var i = 0; i < arr.length; i = i + 1)
flatArr = flatArr.concat(arr[i])
console.log(JSON.stringify(arr))
console.log(JSON.stringify(flatArr))
// [[1],[2,3,[4,5,[6]]],[7,[8,9]]]
// [1,2,3,[4,5,[6]],7,[8,9]]
The concat array method expects one or more arrays as arguments, whose elements will be appended:
[1].concat([2, 3], [4]) // [1, 2, 3, 4]
So if you are using apply, that will flatten another level:
[].concat.apply([1], [[2], [3]]) // === [1].concat([2], [3])
So you can either use push instead of concat, or call (or just direct invocation) instead of apply to get only a single flattening level.
if you use ES6/ES2015 you can use spread operator. Something like this
console.log(...[[[1],[1,2,3,[4,5],4],[2,3]]])

Categories