Below is my input:
input1 =
[{
"201609": 5,
"201610": 7,
"201611": 9,
"201612": 10,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 3,
"201610": 6,
"201611": 9,
"201612": 8
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 1,
"201610": 2,
"201611": 3,
"201612": 5
"FY17": 6,
"careerLevel": "CL1"
},
{
"201609": 2,
"201610": 4,
"201611": 6,
"201612": 9
"FY17": 12,
"careerLevel": "CL2"
}
]
}]
}]
input2 =
[{
"201609": 4,
"201610": 8,
"201611": 12,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 9,
"201610": 2,
"201611": 7,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 3,
"201610": 6,
"201611": 9,
"FY17": 18,
"careerLevel": "CL1"
},
{
"201609": 7,
"201610": 8,
"201611": 9,
"FY17": 24,
"careerLevel": "CL2"
}
]
}]
}]
output = input1 + input2.
My output should have the sum of all the numeric value. If it doesn't
find the matching key like "201612" it should still keep that key in
output.
[{
"201609": 9,
"201610": 15,
"201611": 21,
"201612": 10,
"FY17": 48,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 12,
"201610": 8,
"201611": 16,
"201612": 8,
"FY17": 24,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 4,
"201610": 8,
"201611": 12,
"201612": 5,
"FY17": 24,
"careerLevel": "CL1"
},
{
"201609": 9,
"201610": 12,
"201611": 15,
"201612": 9,
"FY17": 36,
"careerLevel": "CL2"
}
]
}]
}]
Below is what iam trying to do :
var output = [{}];
for(let i in input){
for (let key in input[i]){
if (output[0].hasOwnProperty(key)) {
output[0][key]+=input[i][key];
}else{
output[0][key]=input[i][key];
}
}
}
console.log(JSON.stringify(output)); // errors out
But this is not giving me desired result as it is not able to sum the hierarchical json structure as above.
Let's start by writing the main merge function:
function merge(x, y, fn) {
if (isNotCompound(x) && isNotCompound(y)) {
return fn(x, y);
}
if (isArray(x) && isArray(y)) {
return mergeArray(x, y, fn);
}
if (isObject(x) && isObject(y)) {
return mergeObject(x, y, fn);
}
throw new Error('the two input values are not of the same compound type');
}
The merge function amounts to a dispatching on the type of its input values x and y. If they are both found to be primitive types (i.e., they are not arrays nor objects) they are merged according to the fn function. Otherwise, the proper helper function is selected for proceeding with the traversing.
Let's therefore implement the type predicates necessary for the dispatch:
const isArray = x => Array.isArray(x);
const isObject = x => Object.prototype.toString.call(x) === '[object Object]';
const isNotCompound = x => !isArray(x) && !isObject(x);
It is now a matter of writing mergeArray and mergeObject. One possible implementation for mergeArray is as follows:
function mergeArray(xs, ys, fn) {
if (xs.length !== ys.length) throw new Error('the two arrays must be of the same size');
let r = [];
for (let i = 0; i < xs.length; i++) {
r.push(merge(xs[i], ys[i], fn));
}
return r;
}
As shown, mergeArray requires the two arrays of being of the same size. As for mergeObject, one way of implementing it is as follows:
function mergeObject(obj1, obj2, fn) {
let r = {};
for (let key of Object.keys(obj1)) {
r[key] = obj2[key] ? merge(obj1[key], obj2[key], fn) : obj1[key];
}
for (let key of Object.keys(obj2)) {
if (r[key]) continue;
r[key] = obj2[key];
}
return r;
}
Notably, values are combined for common keys, while unshared properties are directly propagated to the resulting object.
At last, the desired merging strategy can be obtained by passing the following input function:
const isNumber = x => typeof x === 'number';
const add = (x, y) => isNumber(x) && isNumber(y) ? x + y : (x || y);
If the two input, primitive values are both numbers, it returns the sum of them, otherwise it returns whatever of the two happens to be defined.
We can finally execute:
console.log(JSON.stringify(merge(input1, input2, add)));
The whole source code follows.
const isArray = x => Array.isArray(x);
const isObject = x => Object.prototype.toString.call(x) === '[object Object]';
const isNotCompound = x => !isArray(x) && !isObject(x);
function merge(x, y, fn) {
if (isNotCompound(x) && isNotCompound(y)) {
return fn(x, y);
}
if (isArray(x) && isArray(y)) {
return mergeArray(x, y, fn);
}
if (isObject(x) && isObject(y)) {
return mergeObject(x, y, fn);
}
throw new Error('the two input values are not of the same compound type');
};
function mergeArray(xs, ys, fn) {
if (xs.length !== ys.length) throw new Error('the two arrays must be of the same size');
let r = [];
for (let i = 0; i < xs.length; i++) {
r.push(merge(xs[i], ys[i], fn));
}
return r;
}
function mergeObject(obj1, obj2, fn) {
let r = {};
for (let key of Object.keys(obj1)) {
r[key] = obj2[key] ? merge(obj1[key], obj2[key], fn) : obj1[key];
}
for (let key of Object.keys(obj2)) {
if (r[key]) continue;
r[key] = obj2[key];
}
return r;
}
let input1 = [{
"201609": 5,
"201610": 7,
"201611": 9,
"201612": 10,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 3,
"201610": 6,
"201611": 9,
"201612": 8,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 1,
"201610": 2,
"201611": 3,
"201612": 5,
"FY17": 6,
"careerLevel": "CL1"
},
{
"201609": 2,
"201610": 4,
"201611": 6,
"201612": 9,
"FY17": 12,
"careerLevel": "CL2"
}
]
}]
}];
let input2 = [{
"201609": 4,
"201610": 8,
"201611": 12,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 9,
"201610": 2,
"201611": 7,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 3,
"201610": 6,
"201611": 9,
"FY17": 18,
"careerLevel": "CL1"
}, {
"201609": 7,
"201610": 8,
"201611": 9,
"FY17": 24,
"careerLevel": "CL2"
}]
}]
}];
const isNumber = x => typeof x === 'number';
const add = (x, y) => isNumber(x) && isNumber(y) ? x + y : (x || y);
console.log(JSON.stringify(merge(input1, input2, add)));
Create a recursive function and inside that use forEach to iterate the array
The flow is like this instead of looping both the input1 & input2 array , loop over one of them and if the value of the key is an number then add it to the value of same key in another array.If the value of a key is an array then call the same recursive function with new arguuments
var input1 = [{
"201609": 5,
"201610": 7,
"201611": 9,
"201612": 10,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 3,
"201610": 6,
"201611": 9,
"201612": 8,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 1,
"201610": 2,
"201611": 3,
"201612": 5,
"FY17": 6,
"careerLevel": "CL1"
},
{
"201609": 2,
"201610": 4,
"201611": 6,
"201612": 9,
"FY17": 12,
"careerLevel": "CL2"
}
]
}]
}]
var input2 = [{
"201609": 4,
"201610": 8,
"201611": 12,
"FY17": 24,
"metric": "metric1",
"careerLevelGroups": [{
"201609": 9,
"201610": 2,
"201611": 7,
"FY17": 18,
"careerLevel": "Senior Managing Director",
"careerLevels": [{
"201609": 3,
"201610": 6,
"201611": 9,
"FY17": 18,
"careerLevel": "CL1"
},
{
"201609": 7,
"201610": 8,
"201611": 9,
"FY17": 24,
"careerLevel": "CL2"
}
]
}]
}]
// A function which will take input2 and input1 array
function loopArray(arrayToBeLooped, addingArray) {
// now looping over the array
arrayToBeLooped.forEach(function(item, index) {
// item is each object,here checking if the value of object key is array or number
for (let keys in item) {
// if number then find the same key from other array and add the value
if (typeof item[keys] === 'number') {
addingArray[index][keys] = addingArray[index][keys] + item[keys]
}
if (Array.isArray(item[keys])) {
// if the type of value is another array for example
// careerLevelGroups & careerLevels then it is basically same
// as looping over array input1 & input2
// so calling the same loopArray function and passing different
// parameter but the object remains same
loopArray(arrayToBeLooped[index][keys], addingArray[index][keys])
}
}
})
}
loopArray(input2, input1)
console.log(input1)
Related
function addItemEvery(arr, item, starting, frequency) {
for (var i = 0, a = []; i < arr.length; i++) {
a.push(arr[i]);
if ((i + 1 + starting) % frequency === 0) {
a.push(item);
i++;
if(arr[i]) a.push(arr[i]);
}
}
return a;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 1, 1);
console.log(arr);
What I get
[1, "item", 2, 3, "item", 4, 5, "item", 6, 7, "item", 8, 9, "item", 10, 11, "item", 12, 13,
"item", 14, 15, "item", 16]
What i want
[1, "item", 2,"item", 3, "item", 4,"item", 5,"item", "item", 6,"item", 7, "item", 8,"item",
9,"item", "item", 10,"item", 11, "item", 12,"item", 13, "item", 14,"item", 15, "item", 16, "item"]
so please help me check this out i need a function that can help me push to all n index in the array
This will give you the output you desire.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
pos = 1;
interval = 2;
while (pos < array.length) {
array.splice(pos, 0, 'item');
pos += interval;
}
console.log(array);
The base version (excluding the starting and frequency arguments) can be done with a single call to Array#reduce like this. I've excluded starting and frequency since you didn't define their intended behaviour in your question.
const addItemEvery = (arr, el) =>
arr.reduce((res, v) => [...res, v, el], []);
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const output = addItemEvery(input, "item");
console.log(output);
function addItemEvery(arr, item, starting, frequency) {
const newArr = [];
arr.forEach((entry, index) => {
newArr.push(entry);
if (index + 1 >= starting)
for (let i = 1; i <= frequency; i++) {
newArr.push(item);
}
});
return newArr;
}
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 deduplicate an array of arrays. A duplicate array is one that matches a subset of element indices. In this case, say, index [1] and index [3].
const unDeduplicated = [
[ 11, 12, 13, 14, 15, ],
[ 21, 22, 23, 24, 25, ],
[ 31, 88, 33, 99, 35, ], // duplicate in indices: 1, 3 with row index 4
[ 41, 42, 43, 44, 45, ],
[ 51, 88, 53, 99, 55, ], // duplicate in indices: 1, 3 // delete this row from result
];
const deduplicated = getDeduplicated( unDeduplicated, [ 1, 3, ], );
console.log( deduplicated );
// expected result:
// [
// [ 11, 12, 13, 14, 15, ],
// [ 21, 22, 23, 24, 25, ],
// [ 31, 88, 33, 99, 35, ],
// [ 41, 42, 43, 44, 45, ],
// // this row was omitted from result because it was duplicated at indices 1 and 3 with row index 2
// ]
What is a function getDeduplicated() that can give me such a result?
I have tried the below function but it's just a start. And it isn't close to giving me the desired result. But it gives an idea of what I'm trying to do.
/**
* Returns deduplicated array as a data grid ([][] -> 2D array)
* #param { [][] } unDedupedDataGrid The original data grid to be deduplicated to include only unque rows as defined by the indices2compare.
* #param { Number[] } indices2compare An array of indices to compare for each array element.
* If every element at each index for a given row is duplicated elsewhere in the array,
* then the array element is considered a duplicate
* #returns { [][] }
*/
const getDeduplicated = ( unDedupedDataGrid, indices2compare, ) => {
let deduped = [];
unDedupedDataGrid.forEach( row => {
const matchedArray = a.filter( row => row[1] === 88 && row[3] === 99 );
const matchedArrayLength = matchedArray.length;
if( matchedArrayLength ) return;
deduped.push( row, );
});
}
I've researched some lodash functions that might help like _.filter and _.some but so far, I can't seem to find a structure that produces the desired result.
You can create Set out of the values in columns as you iterate over rows. You could choose to create sets only for the designated columns, e.g. 1 and 3 in your case. Then when iterating over each row you check if any of the designated columns in that row has such a value that is already in the corresponding set, and if it does you discard that row.
(On phone, cannot type actual code. And I guess code is pretty straight forward too)
It's probably not the most efficient algorithm, but I'd do something like
function getDeduplicated(unDeduplicated, idxs) {
const result = [];
const used = new Set();
unDeduplicated.forEach(arr => {
const vals = idxs.map(i => arr[i]).join();
if (!used.has(vals)) {
result.push(arr);
used.add(vals);
}
});
return result;
}
Idk if i understand good what you want to do but here is what i've done
list = [
[ 11, 12, 13, 14, 15, ],
[ 21, 22, 23, 24, 25, ],
[ 21, 58, 49, 57, 28, ],
[ 31, 88, 33, 88, 35, ],
[ 41, 42, 43, 44, 45, ],
[ 51, 88, 53, 88, 55, ],
[ 41, 77, 16, 29, 37, ],
];
el_list = [] // Auxiliar to save all unique numbers
res_list = list.reduce(
(_list, row) => {
// console.log(_list)
this_rows_el = [] // Auxiliar to save this row's elements
_list.push(row.reduce(
(keep_row, el) => {
// console.log(keep_row, this_rows_el, el)
if(keep_row && el_list.indexOf(el)==-1 ){
el_list.push(el)
this_rows_el.push(el)
return true
}else if(this_rows_el.indexOf(el)!=-1) return true // Bypass repeated elements in this row
else return false
}, true) ? row : null) // To get only duplicated rows (...) ? null : row )
return _list
}, []
)
console.log(res_list)
This is fairly concise. It uses nested filters. It will also work for any number of duplicates, keeping only the first one.
init = [
[ 11, 12, 13, 14, 15],
[ 21, 22, 23, 24, 25],
[ 31, 88, 33, 99, 35],
[ 41, 42, 43, 44, 45],
[ 51, 88, 53, 99, 55],
];
var deDuplicate = function(array, indices){
var res = array.filter(
(elem) => !array.some(
(el) =>
array.indexOf(el) < array.indexOf(elem) && //check that we don't discard the first dupe
el.filter((i) => indices.includes(el.indexOf(i))).every((l,index) => l === elem.filter((j) => indices.includes(elem.indexOf(j)))[index])
//check if the requested indexes are the same.
// Made a bit nasty by the fact that you can't compare arrays with ===
)
);
return(res);
}
console.log(deDuplicate(init,[1,3]));
Not the most efficient but this will remove dups of more than one duplicate array
const unDeduplicated = [ [ 11, 12, 13, 14, 15, ], [ 21, 22, 23, 24, 25, ], [ 31, 88, 33, 99, 35, ], [ 41, 33, 43, 44, 45, ], [ 51, 88, 53, 99, 55, ]]
const unDeduplicated1 = [
[ 11, 12, 13, 14, 15, ],
[ 21, 22, 23, 24, 25, ],// duplicate in indices: 1, 3 with row index 3
[ 31, 88, 33, 99, 35, ], // duplicate in indices: 1, 3 with row index 4
[ 21, 22, 43, 24, 45, ],// duplicate in indices: 1, 3 // delete this
[ 51, 88, 53, 99, 55, ], // duplicate in indices: 1, 3 // delete this row from result
];
function getDeduplicated(arr, arind) {
for (let i = 0; i < arr.length; i++) {
for (let j = 1 + i; j < arr.length; j++) {
if (arr[j].includes(arr[i][arind[0]]) && arr[j].includes(arr[i][arind[1]])) {
arr.splice(j, 1)
i--
} else continue
}
}
return arr
}
const deduplicated = getDeduplicated(unDeduplicated, [1, 3]);
const deduplicated2 = getDeduplicated(unDeduplicated1, [1, 3]);
console.log(deduplicated)
console.log("#####################")
console.log(deduplicated2)
There are many post about this but I can't figure this one out. This is the json response from an Ajax function:
var obj = {
"3901": 10,
"3900": 3,
"3902": 9,
"3899": 2,
"3274": 4,
"3257": 9.5,
"3883": 12,
"3881": "12",
"3876": 3,
"3267": 14,
"3258": 2.5,
"3260": 13.5,
"3259": 6.5,
"3264": 4.5,
"3268": 2,
"3273": 5.5,
"3266": 17,
"3270": 9,
"3271": 8,
"3275": 2,
"3263": 2.5,
"3261": 2.5,
"3265": "37",
"3281": 3,
"3277": 7.5,
"3278": 0.5,
"3276": 7,
"3898": 8,
"3891": 7,
"3293": 1,
"3895": 1,
"3256": 2,
"3903": 10,
"3840": 2,
"3886": 11,
"3884": 8,
"3872": 2,
"3874": 4,
"3284": 1.5,
"3302": 1.25,
"3304": 5,
"3306": 2,
"3329": 1.5,
"3330": 2,
"3333": 6,
"3335": 7.5,
"3327": 1,
"3934": 8,
"3935": 9,
"3939": 1,
"3933": 3,
"3937": 1,
"3322": 3.5,
"3890": 1,
"3878": 5,
"3880": 4,
"3879": 1,
"3889": 2,
"3852": 2,
"3877": 2
}
I have a this of ids: 3902, 3883, 4567 and 3878
All I need is to loop through the those 4 ids and check if those are in the json response and if they are get the value associated to it and if not return 0. For example:
3902 will return 9 and 4567 will return 0
Thanks.
You can put all the ids into an array called ids, then use .map() on that array. For each id within the array, you can look it up in your object using obj[id]. If it doesn't exist, it will return undefined. If this occurs, you can use a default of 0 by using an ||:
See example below:
const obj = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
const ids = [3902, 3883, 4567, 3878];
const res = ids.map(id => obj[id] || 0);
console.log(res);
var jsonObject = {3256: 2, 3257: 9.5, 3258: 2.5, 3259: 6.5, 3260: 13.5, 3261: 2.5, 3263: 2.5, 3264: 4.5, 3265: "37", 3266: 17, 3267: 14, 3268: 2, 3270: 9, 3271: 8, 3273: 5.5, 3274: 4, 3275: 2, 3276: 7, 3277: 7.5, 3278: 0.5, 3281: 3, 3284: 1.5, 3293: 1, 3302: 1.25, 3304: 5, 3306: 2, 3322: 3.5, 3327: 1, 3329: 1.5, 3330: 2, 3333: 6, 3335: 7.5, 3840: 2, 3852: 2, 3872: 2, 3874: 4, 3876: 3, 3877: 2, 3878: 5, 3879: 1, 3880: 4, 3881: "12", 3883: 12, 3884: 8, 3886: 11, 3889: 2, 3890: 1, 3891: 7, 3895: 1, 3898: 8, 3899: 2, 3900: 3, 3901: 10, 3902: 9, 3903: 10, 3933: 3, 3934: 8, 3935: 9, 3937: 1, 3939: 1}
var ids = [3902, 3883, 4567, 3878];
for(var i =0; i < ids.length; i++)
{
if(temp1.hasOwnProperty(ids[i])) //to check propery exist in JSON object
{
console.log(temp1[ids[i]]) //to read value from JSON object
}
}
I think you already have a valid JSON here.
let data = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
let arr = [3902, 3883, 4567 , 3878];
let ans = arr.map( i => {
if(data[i] === undefined) {
console.log(0);
return 0;
}
else {
console.log(data[i]);
return data[i];
}
});
ans is the required array .
You can use a foreach
j={"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2}
se=[3902, 3883, 4567 , 3878]
res=[]
se.forEach(s=>{
res.push({[s]:j[s]||0})
})
console.log(res)
I am given an input array need to convert to output array (it's consecutive array in the output array.)
var input = [1, 3, 4, 5, 8, 9, 15, 20, 21, 22, 23, 24, 25, 26, 40];
var output = [[1], [3, 4, 5], [8, 9], [15], [20, 21, 22, 23, 24, 25, 26], [40]];
I am able to achieve this by:
let t = 0;
let tArr = []
const a = [];
input.map(i => {
if (i-t === 1) {
tArr.push(i);
} else {
a.push(tArr);
tArr = [];
tArr.push(i)
}
t = i;
});
a.push(tArr);
console.log("final", a)
Can someone suggest a cleaner code or if this could be optimized.
You could reduce the array by looking at the index or ar the former value and compare to the actual value.
var input = [1, 3, 4, 5, 8, 9, 15, 20, 21, 22, 23, 24, 25, 26, 40],
result = input.reduce((r, v, i, a) => {
if (!i || a[i - 1] + 1 < v) {
r.push([v]);
} else {
r[r.length - 1].push(v);
}
return r;
}, []);
console.log(result);