More succinct way to get total number of unique items - javascript

This is my code to get the total number of unique fruit colours by adding each fruit to a set. It is written in 3 lines, I am curious as to whether I can make it into a one-liner code?
const fruitSet = new Set();
allFruits.forEach(fruit => fruitSet.add(fruit.color));
const totalUniqueColors = fruitSet.size;
Update:
I should add that all fruits take this structure and there are >50 fruits:
{
fruit: strawberry
color: red,
price: 2.50
},
{
fruit: watermelon
color: red,
price: 5
},
{
fruit: avocado
color: green,
price: 7
},
{
fruit: banana
color: yellow,
price: 1
},

if you just need the count. you can instantiate a set by passing an iterator into it.
new Set(allFruits.map(({color}) => color)).size

Related

How do I incorporate the index of an array while defining a property of said array within a class in JavaScript?

Sorry if the title makes no sense.. let me explain
Say I have the following 2d array.. the first array representing ice cream and the second representing milkshakes
menu = [ ['vanilla', 'chocolate', 'almond'],
['vanilla', 'pineapple', 'strawberry'] ]
Now I create a class that takes this array as input
class cafe{
constructor(menu){
this.iceCreams = menu[0]
this.milkshakes = menu[1]
}
}
Now I want to define a property called 'price' for each flavor of milkshake.
this.milkshakes[n].price = < a function that computes price based on value of n >
so that i can access them like this :
cafe.milkshakes[0].price
So how do I incorporate the index 'n' of the array while defining the property
I haven't tried anything bcos I dont know how to even approach this ☹️
You can do it in your constructor.
You can grab the names, and call map function on it and do whatever you want. Please check the following example. There, calculatePrice is a function that takes the index and returns the price based on the index.
class Cafe {
constructor (menu) {
this.iceCreams = menu[0].map((flavor, index) => {
return {
flavor,
price: calculatePrice(index)
}
});
this.milkshakes = menu[1].map((flavor, index) => {
return {
flavor,
price: calculatePrice(index)
}
});
}
This is a minimal answer.
UPDATE:
For a detailed and improved answer: https://codesandbox.io/s/cafe-example-wxp2c4
So, in the milkshakes array you need each item as an object data structure, not a string.
menu = [ ['vanilla', 'chocolate', 'almond'],
[{ flavor: 'vanilla' }, { flavor: 'pineapple' }, { flavor: 'strawberry' }] ]
and then you can loop through and set the price, something like this.
menu.milkshakes.forEach((item, index) => item.price = index))
you can use objects:
menu = [
[
{
name: "vanilla",
price: 200,
},
{
name: "chocolate",
price: 200,
},
{
name: "almond",
price: 200,
},
],
[
{
name: "vanilla",
price: 200,
},
{
name: "pineapple",
price: 200,
},
{
name: "strawberry",
price: 200,
},
],
];
and then:
class cafe{
constructor(menu){
this.iceCreams = menu[0]
this.milkshakes = menu[1]
}
}
now iceCreams and milshakes have the property price and name
example:
iceCreams[n].price
iceCreams[n].name

Looping and/or filterering through array with object

Iḿ trying to run through an array with object to get different results as part of an excercise for our IT Bootcamp.
I just can´t seem to get it working. First here is the task.
Create an array of cars. The cars are objects and they have the properties: brand, price, horsepower, color and year_of_construction. Create following cars there:
* `BMW(70000, 200hp, white, 2020)`
* `Mazda(45000, 220hp, silver, 2021)`
* `Volvo(55000, 190hp, beige, 2021)`
* `Opel(38000, 155hp, black, 2021)`
* `Mazda(22000, 90hp, magenta, 2021)`
* `Fiat(19000, 110hp, blue, 2019)`
* Create a loop which filters all cars which cost less than `60000` (means print all properties).
* Create a loop which filters all cars which have more than `150 hp`.
* Create a loop which will print all cars that are made after `2020` and have less than `100 hp`.
* Create a loop which will print all cars that are by `Fiat` or have less than `150 hp`.
Now my code, I can access different indexes in the array, but if I run the code with the loop at the end the console just says (0=)[].
Please help me, somerwhere I don´t get the logic
`
let cars = [
{
Brand: "BMW",
price: 70000,
horsePower: 200,
color: "white",
yearOfConstruction: 2020,
},
{
Brand: "Mazda",
price: 45000,
horsePower: 220,
color: "silver",
yearOfConstruction: 2021,
},
{
Brand: "Volvo",
price: 55000,
horsePower: 190,
color: "beige",
yearOfConstruction: 2021,
},
{
Brand: "Opel",
price: 38000,
horsePower: 155,
color: "black",
yearOfConstruction: 2021,
},
{
Brand: "Mazda",
price: 22000,
horsePower: 90,
color: "magenta",
yearOfConstruction: 2021,
},
{
Brand: "Fiat",
price: 19000,
horsePower: 110,
color: "blue",
yearOfConstruction: 2019,
},
];
let newCars = [];
for (let i=1; i<= cars.lenght; i++){
if (cars[i].price < 60000){
newCars.push(cars[i]);
}
}
console.log(newCars);
`
Thanks for your help.
I tried looking for a solution but we should just use loops and every solution I found uses functions.
There are a few things going on here:
You need to start iterating from 0 rather than 1
You have a spelling error cars.lenght should be cars.length
As #wendt88 pointed out in the comments, it should be < cars.length not <=
I recommend you use a VS Code with the Code Spell extension - it will point out spelling errors for you.
FYI, you can also do this exercise using Array.prototype.filter:
const newCars = cars.filter(car => car.price < 60000)
Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
let filter1 = cars.filter(car => car.price < 60000);
console.log(filter1);
let filter2 = cars.filter(car => car.horsePower > 150);
console.log(filter2)
let filter3 = cars.filter(car => car.yearOfConstruction > 20 && car.horsePower < 100);
console.log(filter3);
let filter4 = cars.filter(car => car.Brand === "Fiat" || car.horsePower < 150);
console.log(filter4);

compare array of data and assign a value

Please i want to extract color name from a user id. The user's id have a short string that indicates the color a user will have
These are the possible colors and codes
pur => purple
ora => orange
bla => black
pnk => pink
users without color
const users = [
{
id: 'u1pur33',
},
{
id: 'u1ora29',
}
]
This is the result i want to achieve
const users = [
{
id: 'u1pur33',
color: 'purple
},
{
id: 'u1ora29',
color: orange
}
]
This is what i have tried so far. i could only add the color to the object but i can't proceed
// create a new array with color
const newUser = users.map(user => ({...user}), color: '')
// colors
const colors = [
{color: 'purple', colorCode: 'pur'},
{color: 'orange', colorCode: 'ora'},
{color: 'black', colorCode: 'bla'},
{color: 'pink', colorCode: 'pnk'}
]
Open up your map with normal braces like this so you can write some code to determine which color to choose.
const colors = {
'pur': 'purple'
....
};
const newUser = users.map(user => {
const code = user.id.substring(2, 5);
return {...user, 'color': colors[code]};
});

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
}

Check if an array contains any element of another array and highlight the ones from another array - React native

I have an array of elements which are displayed as tags. For example:
["apple","banana","pineapple","grape"]
displayed as ==>
apple banana pineapple grape
is the array i have.
For a TextInput onChangeText, a debounced socket-call is initiated with the text entered and after processing i will be getting an array of elements matching the text passed.
For example, I will be getting ["apple","banana"] from the websocket response and it should be displayed in the tags as===>
apple banana pineapple grape
where apple and banana are highlighted.
How to implement it?
--update---
This is how my array looks like
var originalArray = [
{ id: 1, name: "apple" },
{ id: 2, name: "banana" },
{ id: 3, name: "pineapple" },
{ id: 4, name: "grape" },];
];
var receivedArray = [
{ id: 1, name: "apple" },
{ id: 2, name: "banana" },];
You may find all index that the received element appearing in the original array then work on the found indices
var originalArray = ["apple","banana","pineapple","grape"];
var receivedArray = ["apple", "banana"];
var foundIndices = originalArray.map(el => receivedArray.includes(el) ? true : false)
// Highlight copy version of originalArray based on foundIndices
Use a for loop with includes (or even indexOf) perhaps:
function dothing(){
let mainarr=main.value.split(",");
let filtarr=filter.value.split(",");
for(var i=0;i<mainarr.length;i++)
if(filtarr.includes(mainarr[i]))
mainarr[i]="<i><b>"+mainarr[i]+"</b></i>";
log.innerHTML=mainarr.join(" ");
}
dothing();
<input type="text" id="main" oninput="dothing()" value="a,b,c"><br>
<input type="text" id="filter" oninput="dothing()" value="a,b"><br>
<div id="log"></div>

Categories

Resources