Map and filter an array at the same time
You should use Array.reduce
for this.
var options = [ { name: 'One', assigned: true }, { name: 'Two', assigned: false }, { name: 'Three', assigned: true }, ];
var reduced = options.reduce(function(filtered, option) { if (option.assigned) { var someNewValue = { name: option.name, newProperty: 'Foo' } filtered.push(someNewValue); } return filtered;}, []);
document.getElementById('output').innerHTML = JSON.stringify(reduced);
<h1>Only assigned options</h1><pre id="output"> </pre>
How to filter and map nested array items while checking whether the to be filtered items meet certain criteria?
You can do it with one for-of
loop:
const incomplete_items = [];
const new_data = []
for (const [index, item] of data.entries()) {
if(item.productName && item.productCategory && item.productImages.every((image) => image.id && image.content && !['Existing', 'Linked'].includes(image.status))){
new_data.push({
productIndex: index,
name: item.productName,
category: item.productCategory,
filteredImages: item.productImages.map((image) => ({ newcontent: image.content, id: image.id, }))
})
} else {
incomplete_items.push(index);
}
}
Working example
const data = [
{
"productName": null,
"productCategory": null,
"productImages": [
{ "content": "1", "id": null, "data": null, "file": null, "url": null, "status": "Existing" },
{ "content": "","id": "234","data": "test data", "file": "test file", "url": null, "status": "Existing" }
]
},
{
"productName": null,
"productCategory": "hello category",
"productImages": [
{ "content": "1", "id": null,"data": null, "file": null, "url": null, "status": "Existing"},
{ "content": "", "id": "234","data": "test data","file": "test file", "url": null, "status": "Existing" }
]
},
{
"productName": "test product",
"productCategory": "test category",
"productImages": [
{ "content": "1", "id": "123", "data": "test data", "file": "test file", "url": null, "status": "Linked" },
{ "content": "2", "id": "234", "data": "test data", "file": "test file", "url": "test","status": "Linked" }
]
},
{
"productName": "new product",
"productCategory": "new category",
"productImages": [
{ "content": "2","id": "32332", "data": "test data", "file": "test file", "url": "test", "status": "new" }
]
}
]
const incomplete_items = [];
const new_data = []
for (const [index, item] of data.entries()) {
if(item.productName && item.productCategory && item.productImages.every((image) => image.id && image.content && !['Existing', 'Linked'].includes(image.status))){
new_data.push({
productIndex: index,
name: item.productName,
category: item.productCategory,
filteredImages: item.productImages.map((image) => ({ newcontent: image.content, id: image.id, }))
})
} else {
incomplete_items.push(index);
}
}
if(incomplete_items.length) console.log(`Items ${incomplete_items} were missing required properties.`);
console.log(new_data);
How to filter and map array of objects in JavaScript?
You can use Array.filter
and Array.map
to do it, filter using the Array.includes
where you check for the presence of React in the tech
array.
Second step is to map to the desired object by retaining only name
and tech
properties from the original object.
const devs = [{"name":"A","age":26,"tech":["JavaScript","React"],"addr":{"country":"India","city":"Pune"}},{"name":"B","age":25,"tech":["Node","AngularJs"],"addr":{"country":"USA","city":"NY"}},{"name":"C","age":27,"tech":["Java","AWS"],"addr":{"country":"UK","city":"London"}}];const devReact = devs.filter(obj => obj.tech.includes("React")).map(obj => ({"name":obj.name, "tech":obj.tech}));console.log(devReact);
How to join .map and .filter to filter and remove duplicate in object array
If your filter is just to remove duplicates consider creating a Map which simply overwrites all duplicate city.id
s. This can then be converted back to an array, here using spread syntax on the Map.values()
.
const arrayOne = [
{ id: 1, name: 'João', city: { id: 1, name: 'Rio de Janeiro' } },
{ id: 1, name: 'Pedro', city: { id: 2, name: 'Salvador' } },
{ id: 1, name: 'Tiago', city: { id: 1, name: 'Rio de Janeiro' } },
];
const arrayTwo = [...new Map(arrayOne.map(({ city }) => [city.id, city])).values()];
console.log(arrayTwo);
Filter and Map over the same array in React
Like @Yevgen Gorbunkov suggests, what you're doing is fine, filtering before mapping is actually not faster, although it is perhaps, more readable.
But yes, it is possible to do that. Like this:
function Params(props) {
const { Parameters } = useFetchParams();
return (
<div className='Params'>
{
Parameters && Parameters.filter(parameter => parameter.Name.includes(props.filter))
.map(parameter => {
const { Name, Value } = parameter;
return (
<div className='Param' key={Name}>
<p>{Name}</p>
<p>{Value}</p>
</div>
)
})
}
</div>
)
}
Array filter and map at the same time?
flatMap
covers this use case - filtering and mapping at the same time:
arr.flatMap(item => item.revenue || [])
JavaScript how to filter two arrays at the same time
You can implement filter on the array by passing the index, return if index + 1
includes in the resulted array.
Please Note: Since the solution is based on the index, it will not work for the random numbers of array (not sequential).
var one = [1,2,3,4,5];
var two = ["A","B","C","D","E"];
var resultOne = one.filter(v => v == 2 || v == 3 );var resultTwo = two.filter((v,i) => resultOne.includes(i+1));console.log(resultOne);console.log(resultTwo);
Related Topics
Get the Value of Checked Checkbox
Jquery Selector for Id Starts with Specific Text
Getting Unexpected Token Export
How to 'Minify' JavaScript Code
How Do Browsers Pause/Change JavaScript When Tab or Window Is Not Active
Are Es6 Classes Just Syntactic Sugar for the Prototypal Pattern in JavaScript
What Is the Motivation for Bringing Symbols to Es6
How to Create Multidimensional Array
Why Is {} + {} No Longer Nan in Chrome Console
Equivalent of String.Format in Jquery
How to Profile JavaScript Execution
Make Several Requests to an API That Can Only Handle 20 Request a Minute