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));
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 object like this:
const object = {
detectors: [1, 2],
responders: [4, 22],
activators: [5, 23, 31],
enablers: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11],
upgraders: [14, 15, 16, 17, 18, 19, 20, 21, 22],
catalyzer: [12, 29],
chains: [27],
trappers: [13],
finishers: [16],
}
Expected output :
[
{
'detectors': 1,
'responders': 4,
'activators': 5,
'enablers': 1,
'upgraders': 23,
'catalyzer': 12,
'chains': 27,
'trappers': 13,
'finishers': 16,
},
{
'detectors': 2,
'responders': 4,
'activators': 5,
'enablers': 1,
'upgraders': 23,
'catalyzer': 12,
'chains': 27,
'trappers': 13,
'finishers': 16,
},
{
'detectors': 1,
'responders': 22,
'activators': 5,
'enablers': 1,
'upgraders': 23,
'catalyzer': 12,
'chains': 27,
'trappers': 13,
'finishers': 16,
},
{...
And I already wrote a function like this:
object.activators.map((activator, i) => {
return object.detectors.map((detector, i) => {
return object.responders.map((responder, i) => {
return {
detectors: detector,
responders: responder,
activators: activator,
};
});
});
});
I can write another function to flatten the output of the code above, but is there any other way to write the code above into a more general function (not hardcoded) that can apply to any object?
You can use a recursive function to get all permutations from the entries.
const object = {
detectors: [1, 2, 3],
responders: [4, 22],
activators: [1, 2, 3, 4]
};
const getPermutations = obj => {
const res = [];
const entries = Object.entries(obj);
const go = (curr, idx) => {
const key = entries[idx][0];
for(const val of entries[idx][1]){
const next = {...curr, [key]: val};
if(idx !== entries.length - 1) go(next, idx + 1);
else res.push(next);
}
};
go({}, 0);
return res;
}
console.log(getPermutations(object));
I want to sort a 2D array first by column 5, then by column 4. They represent the PTS and GD on a football league table.
var table = [
["teamA", 6, 2, 0, 2, 7],
["teamB", 6, 1, 1, 6, 7],
["teamC", 6, 2, 1, 8, 7]
];
I've adapted the great advice I received on the forum:
Sorting 2D Array by numeric item
I replicated the function so that it first sorts by PTS and then by GD.
console.log(table.sort(comparePTS));
console.log(table.sort(compareGD));
function comparePTS(a, b) {
return b[5] - a[5]
}
function compareGD(a, b) {
return b[4] - a[4]
}
Although this works, it displays the table twice:
Sorted by PTS
[ [ "teamA", 6, 2, 0, 2, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamC", 6, 2, 1, 8, 7 ] ]
Sorted by PTS and GD
[ [ "teamC", 6, 2, 1, 8, 7 ], [ "teamB", 6, 1, 1, 6, 7 ], [ "teamA", 6, 2, 0, 2, 7 ] ]
And this seems the most clunky solution. What's the best way to achieve this within a single function? Thanks in advance.
You could chain the order functions until you have a difference for returning this value to the sorting function.
const
PTS = a => a[5],
GD = a => a[4],
ASC = fn => (a, b) => fn(a) - fn(b),
DESC = fn => (a, b) => fn(b) - fn(a),
sortBy = fns => (a, b) => {
var value;
fns.some(fn => value = fn(a, b));
return value;
};
var table = [["teamA", 6, 2, 0, 2, 7], ["teamB", 6, 1, 1, 6, 7], ["teamC", 6, 2, 1, 8, 7]];
table.sort(sortBy([DESC(PTS), DESC(GD)]));
console.log(table);
.as-console-wrapper { max-height: 100% !important; top: 0; }
I have an array which can be nested multiple times. However, always two arrays with two entries each are at the end of each "nesting". I always need the two entries from the two arrays at the end of each nesting returned.
Here is an example:
const arr = [
[
[1, 2], [3, 4]
], [
[5, 6], [7, 8]
], [
[
[9, 10], [11, 12]
], [
[14, 15], [16, 17]
]
]
];
Here is the expected result:
const return1 = [
{ a: 1, b: 2 },
{ a: 3, b: 4 }
];
const return2 = [
{ a: 5, b: 6 },
{ a: 7, b: 8 }
];
const return3 = [
{ a: 9, b: 10 },
{ a: 11, b: 12 }
];
const return4 = [
{ a: 13, b: 14 },
{ a: 15, b: 16 }
];
Everything I find online is how to reduce an n-nested array to a flat array, something like this:
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16]
You could map with an iterative and recursive approach while checking nested arrays.
var array = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[[9, 10], [11, 12]], [[14, 15], [16, 17]]]],
result = array.reduce(function iter(r, a) {
return r.concat(Array.isArray((a[0] || [])[0])
? a.reduce(iter, [])
: [a.map(([a, b]) => ({ a, b }))]
);
}, []);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
With custom recursive function:
var arr = [[[1, 2], [3, 4]], [[5, 6], [7, 8]], [[[9, 10], [11, 12]], [[14, 15], [16, 17]]]],
result = [],
get_pairs = function(arr, r){
arr.forEach(function(v){
if (Array.isArray(v)) {
if (!Array.isArray(v[0])) {
var o = {a: v[0], b: v[1]};
(!r.length || r[r.length-1].length==2)? r.push([o]) : r[r.length-1].push(o);
} else {
get_pairs(v, r);
}
}
});
};
get_pairs(arr, result);
console.log(result);
Spent to much time in this. However, here is a very messy looking code.
There is this recursive function that checks if a given array is in the form [[number, number],[number, number]]. If so, it adds an object to the variable returnArray that we are knowingly mutating.
If it is not in the form, we just check for the items inside the array.
const arrInput = [
[[1, 2], [3, 4]],
[[5, 6], [7, 8]],
[
[[9, 10], [11, 12]],
[[14, 15], [16, 17]],
],
];
function mapArrayToObj(arr, returnArray = []) {
if (arr.length === 2 && typeof arr[0][0] === "number" &&
typeof arr[0][1] === "number" && typeof arr[1][0] === "number" &&
typeof arr[1][1] === "number") {
returnArray.push([
{ a: arr[0][0], b: arr[0][1] },
{ a: arr[1][0], b: arr[1][1] }
]);
} else {
arr.forEach((item) => { mapArrayToObj(item, returnArray); });
}
return returnArray;
}
console.log(mapArrayToObj(arrInput));