Filtering array based on nested property - javascript

I have an array of objects which has a nested parameter in it and I want to return only those array elements that pass filter based on that nested parameter which is in turn also an array of objects.
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
My aim is to filter only those objects that contain at least one message with status true.
In this example I would expect to get an array of two objects
[{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}
]
Thanks for help and advice!

some() will let you check if a condition is true at least once. You can use that to filter: filter
let arr = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}]
let filtered = arr.filter(item => item.props.messages.some(m => m.status === true))
console.log(filtered)

Use filter.
var result= items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
})
I created this Fiddle:
http://jsfiddle.net/81ue32ra/2/
var items = [{q:1,w:2,props:{p:1, messages:[{status:true},{status:false},{status:true}]}},
{q:3,w:5,props:{p:2, messages:[{status:false},{status:false},{status:false}]}},
{q:7,w:0,props:{p:3, messages:[{status:false},{status:false},{status:true}]}}
];
var result = items.filter(item =>{
return item.props.messages.some(obj => obj.status === true)
});
console.log(result);

Just filter the main array and check if some of the messages status property is true.

let data = your array;
data.filter(obj => obj.props.messages.some(message => message.status).length > 0)

Related

Filter an array within an array of objects

I have an array of 10 users, I want to filter the users based on the 'intresses' (that means interests in dutch) array within the users. So for example I want to filter all the users that have the interests 'Afrika' (like index 2).
This is what I tried but it will give me an empty array back.
var newArray = gesorteerdeMatchPercentages.filter((el) => {
el.intresses.forEach((item) => {
return item.naam === "Afrika";
});
});
console.log("new", newArray);
If i understand you correctly you could do that using Array.prototype.some() like this
var newArray = gesorteerdeMatchPercentages.filter((el) => {
return el.intresses.some(el => el.naam === 'Afrika');
});

How to filter items in the correct orderhow

Consider this array of objects and array of items i want to filter the first array to include only the objects related to the names in Array but follows the order of Array and not the order of object
object= [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
Array= ['max','well','john']
const filterit= object.filter(item=>{
if(Array.includes(item.name)
return item.name
})
console.log(filterit)
the output result is
[{name:'max', age:5},
{name:'john', age:6},
{name:'well',age:12}]
the filter works perfect and only the objects related to names in Array gets filtered the only problem is that it gets filtered according to their order in the 'object' array and not according to the names order in 'Array' so how to fix this in order to get a filtered array in the same order as in Array cause order is very crucial to me
First of all, this filter will not work as expected, as you return the item name, it will filter the items that have falsy value for name.
const filterit= object.filter(item=>{
if(Array.includes(item.name))
return item.name
})
You shouldn't return item.name, but it should return Array.includes(item.name)
const filterit= object.filter(item => Array.includes(item.name))
And to make the array with the same sorting.
let array = [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
let sortedArray = []
let namesArray = ['max','well','john']
namesArray.forEach(name => {
let item = array.find(i => i.name === name)
if (item) sortedArray.push(item)
})
console.log(sortedArray)
Just iterate over the Array itself and filter that obj's array on match
consdt objArr = object= [{name:'ali', age:10},{name:'max', age:5},{name:'john', age:6},{name:'well',age:12}]
const myArr = ['max','well','john']
const result = myArr.filter(elem => {
return objArr.find(item => item.name == elem)
})

Push unique objects into array in JAVASCRIPT

I want to push object that only have unique id1 into array.
Example:
let array = [],
obj = {},
access = true
if(access){
obj['id1'] = 1
obj['id2'] = 2
if(array.indexOf(obj.id1) == -1){
array.push(obj)
}
}
console.log(array);
In the above example I am trying to add value to obj then push the obj into array. But obj.id1 need to be unique. The method I am using above doesn't work in my case.
Thank you
As Taplar says, indexOf will look for the first instance of the thing you pass in in the other array. This won't work because there are no instances of the ids in the array, directly anyway.
Use the find function, which allow you pass in a comparison function, so you can define what a match is.
let initial = [{id:1}, {id:2}, {id:1}];
let result = initial.reduce((acc, item) =>
{
if(!acc.find(other => item.id == other.id))
{
acc.push(item);
}
return acc;
}, []);
console.log(result);
Simplest solution . Lets say myObjArray have duplicate object use below es6 code to get unique array from that
// Creates an array of objects with unique "name" property values.
let uniqueObjArray = [
...new Map(myObjArray.map((item) => [item["name"], item])).values(), ]; console.log("uniqueObjArray", uniqueObjArray);
Refer here for more detail https://yagisanatode.com/2021/07/03/get-a-unique-list-of-objects-in-an-array-of-object-in-javascript/
I think you need to use findIndex and not indexOf.
Try replacing your if condition with the following:
array.findIndex((o)=>{ return o.id1 === obj.id1 }) === -1

Delete an Object from a JavaScript Array [duplicate]

This question already has answers here:
Remove array element based on object property
(12 answers)
Closed 4 years ago.
I have an array like this
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
I would like to delete an object from the array that matches id = 2
Here is my solution
//find the corresponding object
let obj=items.find((item) => item.id=='2');
//loop through the original and delete
Is there any other way to do this more efficiently??
I would like to suggest using splice, this doesn't change the reference of the existing array but just removes the desired element..
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let indexToRemove = items.findIndex((eachElem) => {return eachElem.id == 2})
items.splice(indexToRemove, 1)
console.log(items)
Use Array#filter function for deleting item/s from the array. It actually returns a new array containing those items which corresponds to the predicate.
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let filtered = items.filter(item => item.id !== '2');
console.log(filtered);
For removing from the original array
let items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
let index = items.findIndex(item => item.id === '2');
items.splice(index, 1);
console.log(items);
You can check the console :D
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}, {id:'4',token:'kk'}, {id:'2',token:'kl'}];
items.forEach(item =>{
if(item['id'] == '2') items.splice(items.indexOf(item),1)
})
console.log(items)
You can use splice() with forEach() too:
var items = [{id:'1',token:'jj'},{id:'2',token:'kk'}];
items.forEach((item, index) => {
if(item.id === '2'){
items.splice(index,1);
}
});
console.log(items);

Remove values using condition from multidimensional array using java-script

I have a multidimensional array as following.
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8'],['Top','55','98','90.8'],['Bottom','55','98','90.8']]
I want to remove entire values if it includes 'Top' or 'Bottom', so that i will get a result like this:
[['Base: Values','55','98','90.8'],['Value First','55','98','90.8']]
Somebody give me a solution please. Thanks in advance.
You can filter the array, providing a function to determine if an element should be included or not :
array.filter(e => !e.includes('Top') && !e.includes('Bottom'));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.includes('Top') && !e.includes('Bottom'));
console.log(filtered)
console.log(data)
EDIT: To exclude if any string in array values contains a specific part, you could change the predicate to check if at least one string contains the part:
array.filter(e => !e.some(i => i.includes('part to find')));
Example:
const data = [
['Base: Values','55','98','90.8'],
['Value First','55','98','90.8'],
['Top','55','98','90.8'],
['Bottom','55','98','90.8']
]
const filtered = data.filter(e => !e.some(i => i.includes('Value')));
console.log(filtered)
console.log(data)

Categories