Filtering Nested Array with Lodash/Javascript - javascript

I have the following object array:
var sizeList = [
{ id: 1, title:"Test1",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 2,title:"Test2",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:false}]
},
{ id: 3,title:"Test3",
type:[{name:"Big", present:false}, {name:"Small", present:true}, {name:"Medium", present:true}]
}
]
I want to filter this list where Medium is True. I currently have this set up.
var specificSizes = _.filter(sizeList.type, { 'name': 'Medium', 'present': true })
This keeps returning an empty array. I also tried this:
specificSizes = _.filter(sizeList.type, function (type) {
return _.some(type, {'name': 'Medium', 'present':true})
});

With lodash, you could wrap the condition in the same structure for the test, as the original object.
_.filter(sizeList, { type: [{ name: 'Medium', present: true }] })
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = _.filter(sizeList, { type: [{ name: 'Medium', present: true }] });
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.15.0/lodash.min.js"></script>
In plain Javascript, you could use Array#filter for the outer array and check with Array#some if one condition met.
var sizeList = [{ id: 1, title: "Test1", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 2, title: "Test2", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: false }] }, { id: 3, title: "Test3", type: [{ name: "Big", present: false }, { name: "Small", present: true }, { name: "Medium", present: true }] }],
result = sizeList.filter(function (a) {
return a.type.some(function (b) {
return b.name === 'Medium' && b.present;
});
});
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

Filter Array of objects with nested array

so I am trying to set up a nested filter on an array of objects.
The thing is that the filter is applied inside the object on a key that is another array of objects.
here is the code:
const items = [
{ name: "123", id: 1, value: true, arr: [{ id: 1 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 2 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 3 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 4 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 5 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];
const newArray = items.filter((objects) => {
objects.arr.filter((item) => {
if (item.id === 2) {
return objects;
}
});
});
console.log(newArray);
I 'm not sure where to put the return because in this situation i just get an empty array.
You need to check the nested array contains the wanted id and return the result to the filter method.
const
items = [{ name: "123", id: 1, value: true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] }],
result = items.filter(({ arr }) => arr.some(({ id }) => id === 2));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Use Array#some to check if current arr has an element with id equal to 2:
const items = [ { name: "123", id: 1, value: true, arr: [{ id: 1 }] }, { name: "456", id: 2, value: false, arr: [{ id: 2 }] }, { name: "456", id: 2, value: false, arr: [{ id: 3 }] }, { name: "456", id: 2, value: false, arr: [{ id: 4 }] }, { name: "456", id: 2, value: false, arr: [{ id: 5 }] }, { name: "456", id: 2, value: false, arr: [{ id: 6 }] } ];
const newArray = items.filter(({ arr = [] }) =>
arr.some(({ id }) => id === 2)
);
console.log(newArray);
As you contains only one object in arr then you can access this object by using [0] index.
Working Demo :
const items = [
{ name: "123", id: 1, value: true, arr: [{ id: 1 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 2 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 3 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 4 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 5 }] },
{ name: "456", id: 2, value: false, arr: [{ id: 6 }] },
];
const newArray = items.filter((obj) => {
if (obj.arr[0].id === 2) {
return obj;
}
});
console.log(newArray);
I answered you as per the issue you are facing but if you have multiple objects in your arr then you can go ahead with Array.some() method as suggested by other answers.

Comparing two arrays - removing element from array based on object keys

I have two objects.
const arrayOne = [
{
label: "Categories",
to: "/categories",
id: "product_type",
},
{
label: "Colors",
to: "/colors",
id: "color",
},
{
label: "Materials",
to: "/materials",
id: "material",
},
{
label: "Sizes",
to: "/sizes",
id: "sizes",
},
{
label: "Designers",
to: "/designers",
id: "designer_slug",
},
{
label: "Stores",
to: "/stores",
id: "retailer_slug",
},
];
const arrayTwo = [
{
id: "gender",
label: "Gender",
lazy_loaded: false,
},
{
id: "product_type",
label: "Category",
lazy_loaded: false,
},
{
id: "quick_filters",
label: "Quick filters",
lazy_loaded: false,
},
{
id: "final_price",
label: "Price",
lazy_loaded: false,
},
{
id: "color",
label: "Color",
lazy_loaded: false,
},
{
id: "material",
label: "Material",
lazy_loaded: false,
},
{
id: "designer_slug",
label: "Brand",
lazy_loaded: true,
},
{
id: "retailer_slug",
label: "Store",
lazy_loaded: true,
},
];
As you can see they both have the key 'id'. If the IDs in arrayOne aren't in arrayTwo, I would like them to be removed from arrayOne (the whole object). So in this case, only the object with "sizes" should be removed from arrayOne. How would I go about doing this? Thanks in advance!
you could utilize filter:
const newArrayOne = arrayOne.filter(x => arrayTwo.find(y => y.id === x.id))
You could use a Set with id and filter the other array.
const
arrayOne = [{ label: "Categories", to: "/categories", id: "product_type" }, { label: "Colors", to: "/colors", id: "color" }, { label: "Materials", to: "/materials", id: "material" }, { label: "Sizes", to: "/sizes", id: "sizes" }, { label: "Designers", to: "/designers", id: "designer_slug" }, { label: "Stores", to: "/stores", id: "retailer_slug" }],
arrayTwo = [{ id: "gender", label: "Gender", lazy_loaded: false }, { id: "product_type", label: "Category", lazy_loaded: false }, { id: "quick_filters", label: "Quick filters", lazy_loaded: false }, { id: "final_price", label: "Price", lazy_loaded: false }, { id: "color", label: "Color", lazy_loaded: false }, { id: "material", label: "Material", lazy_loaded: false }, { id: "designer_slug", label: "Brand", lazy_loaded: true }, { id: "retailer_slug", label: "Store", lazy_loaded: true }],
two = new Set(arrayTwo.map(({ id }) => id)),
result = arrayOne.filter(({ id }) => two.has(id));
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }

How to filter nested arrays by searching

I have an array of objects that I want to filter by comparing a nested property to a search term.
For example:
let array = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
},
{
category: 2,
label: "Checkbox1",
diId: 193909,
children: [{ label: "datafound", value: "47d18sb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "045e8786-2165-4e1e-a839-99b1b0ceef57"
}
]
},
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 1,
label: "Empty",
toType: "String",
value: "ebedb43f-4c53-491f-8954-d030321845cd"
},
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
},
{
category: 5,
defaultValueType: 8,
label: "Current Username",
toType: "String",
value: "25f6b40a-33c7-4f17-b29d-99e8d1e4e33c"
},
{
category: 5,
defaultValueType: 9,
label: "Current Location",
toType: "Location",
value: "ed59da2f-318d-4599-9085-4d9d769a27d7"
}
]
},
{
category: 4,
label: "Fixed Value",
isFixed: true,
value: "28e90e3e-a20b-4499-9593-061a7d1e7bd6"
// as you can see there is no children in this object
}
]};
What I'm trying to achieve is if I search for 'nodata' for example my result should be
let array = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
}
]
}
];
Another option if I search for 'spa' my result should be
let array = [
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
}
]
}
];
I have been super confused and I decided to get some help. Thank you for your helps guys!
The following function should do the trick for you:
function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));
if (objHasSearchTerm && !obj.children) return [obj];
const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}
It recursively goes through the data array, looks for any entries that have the specified search term, and if so, places it into the newly constructed object. It will preserve the nested shape of the object, which may or may not be what is needed. Feel free to tweak the algorithm to your own needs.
let allData = [
{
category: 15,
label: "Components",
value: "a614741f-7d4b-4b33-91b7-89a0ef96a099",
children: [
{
category: 1,
label: "Carousel1",
diId: 55946,
// as you can see there are many children nested array of object
children: [{ label: "nodatafoundmessage", value: "47d18fb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "be5e027b-9163-4cfb-8816-0c8e3b816086"
},
{
category: 2,
label: "Checkbox1",
diId: 193909,
children: [{ label: "datafound", value: "47d18sb2-3e63-4542-ad0e-e5e09acb5016", children: [] }],
value: "045e8786-2165-4e1e-a839-99b1b0ceef57"
}
]
},
{
value: "4be22726-850c-4905-ab3b-039fcf607d55",
label: "Default",
children: [
{
category: 5,
defaultValueType: 1,
label: "Empty",
toType: "String",
value: "ebedb43f-4c53-491f-8954-d030321845cd"
},
{
category: 5,
defaultValueType: 2,
label: "Space",
toType: "String",
value: "2d0e1429-572b-4f21-9f83-3340bafff95a"
},
{
category: 5,
defaultValueType: 8,
label: "Current Username",
toType: "String",
value: "25f6b40a-33c7-4f17-b29d-99e8d1e4e33c"
},
{
category: 5,
defaultValueType: 9,
label: "Current Location",
toType: "Location",
value: "ed59da2f-318d-4599-9085-4d9d769a27d7"
}
]
},
{
category: 4,
label: "Fixed Value",
isFixed: true,
value: "28e90e3e-a20b-4499-9593-061a7d1e7bd6"
// as you can see there is no children in this object
}
];
function searchData(dataArray, searchTerm) {
return dataArray.flatMap(obj => {
const objHasSearchTerm = Object.entries(obj)
.some(([key, value]) => key !== 'children' && String(value).toLowerCase().includes(searchTerm.toLowerCase()));
if (objHasSearchTerm && !obj.children) return [obj];
const matchedChildren = searchData(obj.children ?? [], searchTerm);
return objHasSearchTerm || matchedChildren.length > 0
? [{
...obj,
children: matchedChildren,
}]
: [];
})
}
console.log('----- Search: nodata')
console.log(JSON.stringify(searchData(allData, 'nodata'), null, 2))
console.log('----- Search: spa')
console.log(JSON.stringify(searchData(allData, 'spa'), null, 2))

Can you help me with an algorithm?

I'm getting some nested data, that I need to filter out and I just can't wrap my head around all those loops. I would be very glad for a help.
Data I get:
const data = [
{
categories: [{ name: "street" }, { name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }, { name: "architecture" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "architecture" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }],
photo: { childImageSharp: { fluid: "values" } },
},
];
List of photos, each photo has a photo object with source that I ll use to render element and also categories array of objects that contains an name with string value.
And I want to filter out only photos that contains category name "portrait". So I need to create an new array that is filtered with only these results that match my criteria.
What I've tried:
const filtered = data.map((photo) => photo.categories.filter((category) => category.name.includes("portrait")));
What I got:
const result = [
[{name: "portrait"}],
[],
[{name: "portrait"}],
[],
[],
[]
]
What I'd like to get:
const result = [
{
categories: [{ name: "street" }, { name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
}
]
Dont use map just use filter
const data = [
{
categories: [{ name: "street" }, { name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "portrait" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }, { name: "architecture" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "architecture" }],
photo: { childImageSharp: { fluid: "values" } },
},
{
categories: [{ name: "street" }],
photo: { childImageSharp: { fluid: "values" } },
},
];
const result = data.filter( x => x.categories.some(c => c.name == "portrait"));
console.log(result);

how to filter nested array like this?

I am having response like below
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
If i search m the filter should be like this
[
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search master the filter response should like this?
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search xxx-master the filter response should be
[
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
if i search slkvcsmcskc filter response like
[]
my typescript code is not working properly .please help me to fix this>
m.filter(x=> x.name.toLowerCase() === search.toLowerCase() || x.subList.some(x1=> x1.name.toLowerCase()===search.toLowerCase()))
The following code gives the desired output. Note that I added some complexity which may not be needed for your use case. However, the example should work for lists with arbitrary deep nesting (see 'bar' example).
let m = [
{
name: 'Summary',
subListExpanded: false,
subList: [
]
},
{
name: 'Upload',
subListExpanded: false,
subList: [
{
name: 'foo',
subList: [
{
name: 'bar',
}
],
}
]
},
{
name: 'Tasks',
subListExpanded: false,
subList: [
]
},
{
name: 'Dashboard',
subListExpanded: false,
subList: [
]
},
{
name: 'Master',
subListExpanded: false,
subList: [
{
id: 'user-master',
name: 'User-Master'
},
{
id: 'menu-master',
name: 'Menu-Master'
},
{
id: 'entity-master',
name: 'Entity-Master'
},
{
id: 'vendor-master',
name: 'Vendor-Master'
},
{
id: 'xxx-master',
name: 'xxx-Master'
}
]
}
];
function search (input, query) {
const queryReg = new RegExp(query, 'i');
function searchInternal (data) {
let result = [];
data.forEach(item => {
const parentMatch = queryReg.test(item.name);
let subMatch = false;
if (item.subList) {
let subResult = searchInternal(item.subList);
subMatch = subResult.length > 0;
item.subList = subMatch ? subResult : [];
}
// push parent if it matches for itself or a child (list) matches
if (parentMatch || subMatch) result.push(item);
});
return result;
}
return searchInternal(JSON.parse(JSON.stringify(input)) /* create a working copy with JSON.parse(...) */);
}
console.log('master', search(m, 'master'));
console.log('xxx-master', search(m, 'xxx-master'));
console.log('m', search(m, 'm'));
console.log('bar', search(m, 'bar'));
console.log('slkvcsmcskc', search(m, 'slkvcsmcskc'));
Actually it should go like this:
obj = {
_id: "sjkd9skj",
data: {
dektop: [
{
x: 2,
y: 3,
t: { key: 'aabbcc'}
},
...
],
mobile: [
{
x: 4,
y: 3,
t: { key: 'ffff'}
},
...
],
print: [
{
x: 7,
y: 5,
t: { key: 'ppp'}
},
...
]
}
}

Categories