How to get length of sub items in array - javascript

I want to get the total length number of items under arraycompany for example in below example it should be 5, do you have an idea how to do it in java script. thanks
this is my json:
var json ={
"market": [
{
"company": [
{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
},
{
"company": [
{
"name": "D"
},
{
"name": "E"
}
]
}
]
}

json.market.reduce((acc, market) => acc + market.company.length, 0)

Use reduce function and update the value of the accumulator
var json = {
"market": [{
"company": [{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
},
{
"company": [{
"name": "D"
},
{
"name": "E"
}
]
}
]
}
var x = json.market.reduce(function(acc, curr) {
// acc mean the accumulator, 0 was passed as the first value
acc += curr.company.length;
return acc;
}, 0) // 0 is the initial value
console.log(x)

this code may be helpful.
var totallength=0;
json.market.reduce(function(i,o){totallength+=o.company.length;},0);
console.log(totallength)

I'm also posting here a solution using lodash, a bit more complicated, but generic. Which means it's gonna count the total elements of every property:
const data = {
market: [
{ company: [1, 2, 3], address: [1, 2, 4], test: [6,7]},
{ company: [4, 5, 6], address: [3, 4], bonus: [9] }
]
};
// get the length of every array (this can actually be done without lodash with Object.keys(obj).forEach...)
temp = data.market.map(obj => _.mapValues(obj, o => o.length));
counter = {}
temp.forEach(arr => Object.keys(arr).forEach(el => (counter[el] = (counter[el] || 0) + arr[el])))
// counter = { company: 6, address: 5, test: 2, bonus: 1 }

You can use Array.prototype.reduce() to get the result
Code:
const json = {
"market": [{
"company": [{
"name": "A"
},
{
"name": "B"
},
{
"name": "C"
}
]
},
{
"company": [{
"name": "D"
},
{
"name": "E"
}
]
}
]
};
const result = json.market.reduce((a, c) => a + c.company.length, 0);
console.log(result);

Related

How to Filter Nested Object Array Without affecting References in JavaScript

Just want to remove all the items other than 14 from the parentId: 1001 and add that item to another object.
I want to filter the array without affecting the source array.
var Data = [{
"id": 1001,
"text": "A",
"items": [
{ "id": 13, "text": "Thirteen" },
{ "id": 14, "text": "Fourteen" },
{ "id": 15, "text": "Fifteen", }
]
},
{
"id": 1002,
"text": "B",
"items": [
{ "id": 21, "text": "TwentyOne" },
{ "id": 22, "text": "TwentyTwo" },
{ "id": 23, "text": "TwentyThree", }
]
}
]
var childId = 14;
Data.items.filter((x) => {
return x.id != childId;
})
//this is affecting the source array (Data)
//after searching on internet found a solution
Data.items.filter((x) => {
return x.id childId;
}).map(function(x) {
return x
});
Your Data has no items property: it is an array, so you actually have Data[0].items, Data[1].items, ...
NB: it is common practice to use camelCase for such variable names, and reserve PascalCase for constructors/classes
Here is how you could do it:
const data = [{"id": 1001,"text": "A","items": [{ "id": 13, "text": "Thirteen" }, { "id": 14, "text": "Fourteen" }, { "id": 15, "text": "Fifteen", }]},{"id": 1002,"text": "B","items": [{ "id": 21, "text": "TwentyOne" }, { "id": 22, "text": "TwentyTwo" }, { "id": 23, "text": "TwentyThree", }]}]
const childId = 14;
const newData = data.map(obj => ({
...obj,
items: obj.items.filter(x => x.id != childId)
}));
console.log(newData);
As you want to filter out a few items from an array object and want to add those into another object.
You can also achieve this requirement by doing a deep copy of an original array with the help of structuredClone() API and then iterating it using Array#forEach method.
Live demo :
const data=[
{
"id":1001,
"text":"A",
"items":[
{
"id":13,
"text":"Thirteen"
},
{
"id":14,
"text":"Fourteen"
},
{
"id":15,
"text":"Fifteen",
}
]
},
{
"id":1002,
"text":"B",
"items":[
{
"id":21,
"text":"TwentyOne"
},
{
"id":22,
"text":"TwentyTwo"
},
{
"id":23,
"text":"TwentyThree",
}
]
}
];
const clone = structuredClone(data);
let remainingItems = [];
clone.forEach(obj => {
if (obj.id === 1001) {
remainingItems = obj.items.filter(({ id }) => id !== 14);
obj.items = obj.items.filter(({ id }) => id === 14);
} else {
obj.items = [...obj.items, ...remainingItems];
}
})
console.log('cloned data_____', clone);
console.log('source data_____', data);

How to filtering out the multiple nested object in Javascript object

Javascript
I have a nested array of objects, I'm trying to filter the given array of objects using a property from the third level of its array property value. For example, from the below array I like to filter the entire array using the property ListId: 10
Example
let test = {
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":11,
"name":"string2",
"state":"BY"
},
{
"ListId":12,
"name":"string3",
"state":"BY"
}
]
}
]
},
{
"name":"header2",
"value":[
{
"id":"01",
"list":[
{
"ListId":100,
"name":"string1",
"state":"BY",
"techId":0
},
{
"ListId":111,
"name":"string2",
"state":"BY"
},
{
"ListId":121,
"name":"string3",
"state":"BY"
}
]
}
]
}
]
}
Filtervalue with ListId = 10
Expected output :
{
"test":true,
"group":[
{
"name":"header",
"value":[
{
"id":"0",
"list":[
{
"ListId":10,
"name":"string1",
"state":"BY",
"techId":0
}
]
}
]
}
]
}
How can I use the filter method using javascript to get this expected result?
You can two it in two times :
First, filter the list arrays,
Secondly filter the groups array using the some method
let test= {
"test": true,
"group": [
{
"name": "header",
"value": [
{
"id": "0",
"list": [
{
"ListId": 10,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 11,
"name": "string2",
"state": "BY"
},
{
"ListId": 12,
"name": "string3",
"state": "BY"
}
]
}
]
},
{
"name": "header2",
"value": [
{
"id": "01",
"list": [
{
"ListId": 100,
"name": "string1",
"state": "BY",
"techId": 0
},
{
"ListId": 111,
"name": "string2",
"state": "BY"
},
{
"ListId": 121,
"name": "string3",
"state": "BY"
}
]
}
]
}
]
}
test.group.forEach(group => {
group.value.forEach(value => {
value.list = value.list.filter(list => list.ListId === 10)
})
})
test.group = test.group.filter(group => group.value.some(value => value.list.length > 0))
console.log(test)
Note : You should use plural names for you arrays, it helps understanding the data. For example lists not list for the array.
let z ={"group1": [
{
"name": "header",
"value": [
{
"id": 0,
"list": [
{
"ListId": 10,
"Name": "string1"
},
{
"ListId": 11,
"Name": "string2"
}
]
}
]
}
]}
// This function was written from understading that 'group1' is not a fixed property, but part of a dynamic list due to the number '1'
const getItemByListId = (list, listId) => {
const listKeys = Object.keys(list);
const selectedListKey = listKeys.find(key => {
const groupItems = list[key];
const selectedItem = groupItems.find(({ value: nestedItems }) => {
const selectedNestedItem = nestedItems.find(({ list }) => {
const selectedList = list.find(({ ListId }) => ListId === listId)
return selectedList;
});
return selectedNestedItem;
});
return selectedItem;
});
if (!selectedListKey) {
return null;
}
return list[selectedListKey];
};
console.log(getItemByListId(z, 10));

Group an array of objects based on a specific field

I have an array of objects. I want to group them by a specific field.
[
{
"name": "JOHN",
"type": 1,
"sum": 5
},
{
"name": "SERA",
"type": 1,
"sum": 43
},
{
"name": "SERA",
"type": 2,
"sum": 129
},
{
"name": "JOHN",
"type": 2,
"sum": 200
}
]
The output I expect for grouping by name attribute is as follows.
{
// Group #1
"JOHN": [
{
"type": 2,
"sum": 200
}
{
"type": 1,
"sum": 5
}
],
// Group #2
"SERA":[
{
"type": 1,
"sum": 43
},
{
"type": 2,
"sum": 129
},
]
}
I used nested loops, but unfortunately the execution speed was slow and it did not give the right results.
As if you mentioned, we can use an object instead of an array for the most outer wrapper. And also swap inside one object to an array, then this is a possible solution.
var data = [{"name": "JOHN","type": 1,"sum": 5},{"name": "SERA","type": 1,"sum": 43},{"name": "SERA","type": 2,"sum": 129},{"name": "JOHN","type": 2,"sum": 200}];
var newData = {};
data.forEach( (item) => {
if (!(item['name'] in newData)) {
newData[item['name']] = [];
}
newData[item['name']].push(
{
'type': item['type'],
'sum' : item['sum']
}
);
});
console.log(newData);
Your proposed output structure is not valid, however using Array.reduce you can create an object in which all the properties are arrays of objects:
const data = [
{
"name": "JOHN",
"type": 1,
"sum": 5
},
{
"name": "SERA",
"type": 1,
"sum": 43
},
{
"name": "SERA",
"type": 2,
"sum": 129
},
{
"name": "JOHN",
"type": 2,
"sum": 200
}
];
const result = data.reduce((c, {name, type, sum}) => {
c[name] = c[name] || [];
c[name].push({type, sum});
return c;
}, {});
console.log(result);
One more way with forEach, destructuring and ?? operator
const merge = (arr) => {
const obj = {};
arr.forEach(({ name, ...rest }) => (obj[name] ??= []).push(rest));
return obj;
};
const data = [
{
name: "JOHN",
type: 1,
sum: 5,
},
{
name: "SERA",
type: 1,
sum: 43,
},
{
name: "SERA",
type: 2,
sum: 129,
},
{
name: "JOHN",
type: 2,
sum: 200,
},
];
console.log(merge(data));
You can use this function which take advantage of Array.prototype.reduce to transform the initial data to another structure of array.
let data = [
{
"name": "JOHN",
"type": 1,
"sum": 5
},
{
"name": "SERA",
"type": 1,
"sum": 43
},
{
"name": "SERA",
"type": 2,
"sum": 129
},
{
"name": "JOHN",
"type": 2,
"sum": 200
}
];
function groupedBy(data, field) {
let fieldValues = [...data].reduce((acc, current) => {
return acc.concat(current[field]);
}, []).filter((value, index, self) => {
return self.indexOf(value) === index;
});
let results = fieldValues.reduce((acc, item) => {
let items = [...data].filter(el => {
return el.name === item;
});
items.forEach(i => delete i.name);
return Object.assign(acc, { [item]: items});
}, {});
return results;
}
console.log(groupedBy(data, "name"));

Javascript array of arrays that contains obj, take only arrays that contain an obj with a specific key

I have array of arrays that contains obj, I should only take arrays that contain an obj with a specific key.
I tried to use a double filter but it doesn't work.
Can you give me some advice?
let result = [
[
{
"id": 1
},
{
"id": 2
}
],
[
{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[
{
"id": 6,
"type": {
"id": 5456
}
}
]
];
const c = result.filter(array => array.filter(a => a.hasOwnProperty('type') === true));
console.log(c);
Result:
[
[
{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[
{
"id": 6,
"type": {
"id": 5456
}
}
]
]
The filter in your filter function is wrong because you don't want to return a new collection, you want to return a boolean expression. Array.some() helps and checks if any item in that subarray has this property.
let result = [
[{
"id": 1
},
{
"id": 2
}
],
[{
"id": 3
},
{
"id": 4
},
{
"id": 5,
"type": {
"id": 1555
}
}
],
[{
"id": 6,
"type": {
"id": 5456
}
}]
];
const validArrays = result.filter(subArray => subArray.some(item => item.hasOwnProperty('type')));
console.log(validArrays);
You'll have to check whether the length of the return value from the inner array is > 0. Only if the length of the return value from the inner filter is > 0 the outer filter returns true and store it into validArrays.
let result = [[{"id":1},{"id":2}],[{"id":3},{"id":4},{"id":5,"type":{"id":1555}}],[{"id":6,"type":{"id":5456}}]];
const validArrays = result.filter(subarray => subarray.filter(item => item.hasOwnProperty('type') === true).length > 0);
console.log(validArrays);

Convert array of object values from int to string

I have the following array
[ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }
How can I convert that to
[ { "id": '1', "name": "Test" }, { "id": '2', "name": "Test2" }
For all the objects in an array, you want to convert a property type from number to string. You can use Array.forEach to achieve the same.
let arr = [ { "id": 1, "name": "Test" }, { "id": 2, "name": "Test2" }];
arr.forEach(v => v.id += '');
console.log(arr);

Categories