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; }
Related
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 ] }
]
I have to convert matrix to array. For example
[
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
]
should convert to [1, 2, 3, 6, 5, 4, 7, 8, 9 ].
I write a code
function sortMatrix (matrix) {
let newArr = [];
for(let i = 0; i < matrix.length; i++)
{
newArr = newArr.concat(matrix[i]);
}
return newArr
}
but output is [1, 2, 3, 4, 5, 6, 7, 8, 9 ]. How can I do so that on the second line, it counts from the end
To fix your code - reverse sub-arrays at odd indexes.
Note: since Array.reverse() mutates the original array, we need to shallow clone it using array spread.
function sortMatrix(matrix) {
let newArr = [];
for (let i = 0; i < matrix.length; i++) {
const arr = matrix[i];
newArr = newArr.concat(i % 2 ? [...arr].reverse() : arr);
}
return newArr;
}
const matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
];
const result = sortMatrix(matrix);
console.log(result);
Another option is to use Array.flatMap(), and reverse sub-arrays at odd indexes.
function sortMatrix(matrix) {
return matrix.flatMap((arr, i) => i % 2 ? [...arr].reverse() : arr);
}
const matrix = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
];
const result = sortMatrix(matrix);
console.log(result);
You can use reduce to create it.
const arr = [
[1,2,3],
[4,5,6],
[7,8,9]
]
const flatArray = (arr) => arr.reverse().reduce((acc, curr)=> {
acc.push(...curr.reverse());
return acc;
},[])
console.log(flatArray(arr))
You can directly use the flat function
array = [
[ 1, 2, 3 ],
[ 4, 5, 6 ],
[ 7, 8, 9 ],
]
console.log(array.flat());
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));
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));
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]]])