how to compare array.include(arrayData) in vue - javascript

i have two array data
checked: [
'orange', 'apple', 'juice'
]
and 2nd
products: [
'0': {
title: 'this is product title',
categories: [
'apple', 'juice'
]
}
]
i want to to filter data with computed property with checkbox
i tried this
computed: {
filterProducts(){
return this.products.filter(product => this.checked.includes(product.categories));
}
}
but its not working how can i do this

You can use .every() for that.
Here is an example:
checked = [
'orange', 'apple', 'juice'
]
products = [{
title: 'this is product title',
categories: [
'apple', 'juice'
]
}];
const filteredProducts = products.filter(({ categories }) => categories.every(cat => checked.includes(cat)));
console.log(filteredProducts);
This will return an array of products that have a categories array with all its values included in the checked array.
I'm not sure if this is exactly what you're trying to do, if you instead want to get all the products with a categories array that has at least one of its values in the checked array, use .some() instead of .every().

You're trying to check if an array of strings includes an array (which won't work even if your initial array contained arrays). Instead of using .includes(), use .every() on product.categories to check if all items within this array are contained within checked:
const checked = ['orange', 'apple', 'juice'];
const products = [
{
title: 'this is product title',
categories: ['apple', 'juice']
}
];
const computed = products.filter(product => product.categories.every(item => checked.includes(item) || !checked.length));
console.log(computed);

Related

Test array of objects for values equal to values from another array in Chai

I'm totally new to Chai, and this is probably really simple, but I can't find any reference to my case in the official docs. I'm trying to verify that an array with two objects has a property value exactly matching values in another array.
Consider the following:
test('Array includes ids', function() {
const array1 = [
{
type: 'type1',
id: '1'
},
{
type: 'type2',
id: '2'
},
]
const array2 = ['1', '2']
chai.expect(array1).to.have.deep.members(array2) // fails
})
I'd like to verify that objects in array1 has an id property with one of the values found in array2. I know I could map array1 as array1.map(p => p.id) and compare that with array2, but that seems to go against testing as a practice. After all, I don't want to tamper too much with my target to make it conform to my current level of knowledge.
Is there a better way to test this? (Needless to say, my example code above does not work as desired.)
Just transform your array1 with .map() method to have your kind of array with only ids in it just like array2,
test('Array includes ids', function() {
const array1 = [
{
type: 'type1',
id: '1'
},
{
type: 'type2',
id: '2'
},
]
const arr1 = array1.map(e=>e.id);//transform with .map() -> ['1', '2']
const array2 = ['1', '2']
chai.expect(arr1).to.have.deep.members(array2) // pass
})

Javascript filter parent array based on child containing value

I am trying to filter the parent array products based on the selected value which should be contained as the child. For example in my case I was trying to get all the product objects as an array which contained the string "iphone". It is not working for me and I can't seem to locate my error. Please may someone help.
What I have tried:
const selected = 'iphone'
const products = [
{
id: "4irnflpd0",
productItem: [ "iphone", "ipad", "kindle"],
},
{
id: "glrscb1m3s9k",
productItem: ["airpods","iphone",],
},
{
id: "uumkugk3jxof",
productItem: ["macbook","cable"]
},
]
var filtered = products.map(o=>{
o = Object.assign({},o); //Clone the object. So any changes will not affect the original array.
o.productItem.map(p=>{ //Use map to loop thru the products
p = p.filter(v=>v === selected); //Filter the products which include selected
});
return o;
})
Expected array output:
const products = [
{
id: "4irnflpd0",
productItem: [ "iphone", "ipad", "kindle"],
},
{
id: "glrscb1m3s9k",
productItem: ["airpods","iphone",],
},
]
Just a simple filter() method should work for us in this case. T further simplify, we can also use object restructuring, so instead of writing product.productItem.includes(selected), we'll only need to write productItem.includes(selected).
All we have to do is filter the source array by which items include the selected value:
const selected = 'iphone';
const products = [
{ id: "4irnflpd0", productItem: ["iphone", "ipad", "kindle"] },
{ id: "glrscb1m3s9k", productItem: ["airpods", "iphone", ] },
{ id: "uumkugk3jxof", productItem: ["macbook", "cable"] },
];
const filtered = products.filter(({productItem}) => productItem.includes(selected));
console.log(filtered);
If you'd prefer not to use Object destructuring, just swap that filter line for this more traditional one:
products.filter(p => p.productItem.includes(selected))
If you're not sure that every single item in your array will have the productItem key, then you should use optional chaining to prevent an error being thrown. This is as simple as adding ? before after property name. Here it is all put together:
products.filter(p => p.productItem?.includes(selected))
First of all no need to make a copy since with map function you allocated the result to new variable without changing the new array
So you need to do this
const filtered = products.map(p=>{
return p.productItem.includes(selected)
})
You can use the filter() methods on products array and find if the selected item is available in the productItems
const selected = 'iphone'
const products = [
{ id: "4irnflpd0", productItem: [ "iphone", "ipad", "kindle"] },
{ id: "glrscb1m3s9k", productItem: ["airpods","iPhone",] },
{id: "uumkugk3jxof", productItem: ["macbook","cable"] }
]
var filtered = products.filter(product =>
product.productItem?.includes(selected));
console.log(filtered);

How to retrieve certain properties of an array of objects and put it into a new array of objects? [duplicate]

This question already has answers here:
Filter array of objects based on another array in javascript
(10 answers)
Closed 2 years ago.
i have an array of objects like below,
data: [
{
name: 'name1',
id: '1',
description: 'name 1 description',
},
{
name: 'name2',
id: '2',
description: 'name 2 description',
},
{
name: 'name3',
id: '3',
description: 'name 3 description',
},
]
i have an array consisting of ids like so
const id_list = ['1','2'];
Now i want to retrieve the id and name from data array object whose id matches with id_list
so the expected output is
const new = [
{
id: '1',
name: 'name1',
},
{
id: '2',
name: 'name2',
}
]
i am new to using react, javascript or typescript. could someone help me solve this. thanks.
what i have tried?
i know that to filter the value based on one value
so if i have to filter based on one id say '1'
i can do
const new = data.filter((item) => id === item.id);
but in my case i want to filter all items which match the id_list array and should retrieve only matching object name and id and put it to a array.
You can use the map function with a find method to map every id of id_list to the corresponding object in data
const result = id_list.map((id) => data.find((d) => d.id === id));
After that you have all objects that were found by ids in result. You can either only use the props you want or map again and get only the required properties.
const final = result.map(({ id, name })=> ({ id, name }))

office-ui-fabric / fluent-ui Grouped DetailsList

Today I tried to use the Grouped DetailsList of the fluent-ui.
What I expected: I need to declare some groups, let's say red, blue, green and then just add to each item, I want to add to the List, a specific property, that maps the Item to the groups.
e.g.:
groups: [
{ key: 'red', name: 'Color: "red"'},
{ key: 'green', name: 'Color: "green"'},
{ key: 'blue', name: 'Color: "blue"' },
],
items: [...,
{ key: 'red',anyProp1: "abc", anyProp2: "dfg",...},
...,
]
What I found out I have to do: I need to sort the Array, which contains my items in that way, that all Items belonging to the Group red need to be in one block. e.g.: [red, red, red, blue, blue, green, green, green]. Now I needed to provide the information about startIndex and count to map my Array of items to the groups.
This is what a definition of a group could look like:
groups: [
{ key: 'groupred0', name: 'Color: "red"', startIndex: 0, count: 2, level: 0 },
{ key: 'groupgreen2', name: 'Color: "green"', startIndex: 2, count: 0, level: 0 },
{ key: 'groupblue2', name: 'Color: "blue"', startIndex: 2, count: 3, level: 0 },
],
I can't understand why they have done it this way (For me it's very inconvenient this way). So, while I'm more between a beginner and an intermediate in JS. I think the guys who implemented this are professionals. There must be a reason. Maybe it has something todo with performance? I could imagine that when it comes to very large lists, it performs better this way, but I'm not sure.
Does anybody knows some details about this and can explain?
Faced the same issue and got a clue here. Then bult my solution.
Following is the function to generate groups array from the given items list sorted by the grouping column:
function groupsGenerator(itemsList, fieldName) {
// Array of group objects
const groupObjArr =[]
// Get the group names from the items list
const groupNames = [...new Set(itemsList.map(item => item[fieldName]))]
// Iterate through each group name to build proper group object
groupNames.forEach(gn => {
// Count group items
const groupLength = itemsList.filter(item => item[fieldName] === gn).length
// Find the first group index
const groupIndex = itemsList.map(item => item[fieldName]).indexOf(gn)
// Generate a group object
groupObjArr.push({
key: gn, name: gn, level: 0, count: groupLength, startIndex: groupIndex
})
})
// The final groups array returned
return groupObjArr
}
Typed and with empty group name option variant of the Timus's answer
function generateGroups(items: any[], fieldName: string, emptyGroupName: string = '-'): IGroup[] {
const groups: IGroup[] = []
const groupNames = [...new Set<string>(items.map(item => item[fieldName]))]
groupNames.forEach(name => {
const groupItemsCount = items.filter(item => item[fieldName] === name).length
const groupStartIndex = items.map(item => item[fieldName]).indexOf(name)
groups.push({
key: name,
level: 0,
name: name ?? emptyGroupName,
count: groupItemsCount,
startIndex: groupStartIndex
})
})
return groups
}

json object from javascript nested array

I'm using a nested array with the following structure:
arr[0]["id"] = "example0";
arr[0]["name"] = "name0";
arr[1]["id"] = "example1";
arr[1]["name"] = "name1";
arr[2]["id"] = "example2";
arr[2]["name"] = "name2";
now I'm trying to get a nested Json Object from this array
arr{
{
id: example0,
name: name00,
},
{
id: example1,
name: name01,
},
{
id: example2,
name: name02,
}
}
I tought it would work with JSON.stringify(arr); but it doesen't :(
I would be really happy for a solution.
Thank you!
If you are starting out with an array that looks like this, where each subarray's first element is the id and the second element is the name:
const array = [["example0", "name00"], ["example1", "name01"], ["example2", "name02"]]
You first need to map it to an array of Objects.
const arrayOfObjects = array.map((el) => ({
id: el[0],
name: el[1]
}))
Then you can call JSON.stringify(arrayOfObjects) to get the JSON.
You need to make a valid array:
arr = [
{
id: 'example0',
name: 'name00',
},
{
id: 'example1',
name: 'name01',
},
{
id: 'example2',
name: 'name02',
}
];
console.log(JSON.stringify(arr));
Note that I am assigning the array to a variable here. Also, I use [] to create an array where your original code had {}.

Categories

Resources