I have this simple code that works. However it feels cheesy and like I am doing something stupid.
So is this how I would handle this if I wanted to be in one line?
let lifeColors = [
{ lives: 1, color: 'lime' },
{ lives: 2, color: 'orange' },
{ lives: 3, color: 'salmon' },
]
let lives = 20;
let color = (lifeColors.find(x => x.lives === lives) || {color: 'white'}).color;
console.log(color)
My inspiration was from this post
JS: Handle with find() property undefined
Related
Hi guys i got a complicated case for me
I have 4 array like this
[
{
"Id":1111111,
"OptionName":"Color",
"VariantName":"White"
},
{
"Id":2222222,
"optionName":"Size",
"VariantName":"XL"
},
{
"Id":3333333,
"OptionName":"Color",
"VariantName":"GREEN"
},
{
"Id":4444444,
"optionName":"Size",
"VariantName":"L"
}
]
So i want to merge the ID like
1 on 1, 1 on 2,2 on 1, 2 on 2
The result should be like this, but depend by variant name, so colours merge to size
[
{
"Id":1111111_2222222
...
},
{
"Id":1111111_4444444,
...
},
{
"Id":3333333_2222222,
...
},
{
"Id":3333333_4444444,
...
}
]
I already found how to group them by option Name, but how to merge it?
this is the code how i group them
const filteredVariantCats = variantCats
.map((a) => a.optionName)
.filter(onlyUnique)
.map((optionName) => {
let array = []
return variantCats
.filter((a) => a.optionName === optionName)
.map((a, idx) => {
array.push(a)
return a
})
})
UPDATE RESULT THAT I WANT TO RETURN IS THIS
{
id: null,
combinationStr: a.ID+"_"+b.ID,
name: a.variantName+' ,'+ b.variantName,
hex: '#000',
stock: 0,
price: 0,
priceDiscountType: OPTION.DISCOUNT_TYPE.NONE,
priceDiscount: 0,
weight: 10,
code: '',
attributeCode: 'a',
active: true,
productId: product.id from state,
}
Assume the syntax error and mis-matched cases are just error you make while writing the example and not actual mistakes in your actual code. If I understand correctly, you want to split the array into two groups, colors and sizes. Then generate all combinations between the two. Here is an example of how to do so. Since you mark ... in your expected output, I don't know what you actually expect so can only provide the Id field.
const arr = [
{
Id: 1111111,
OptionName: "Color",
VariantName: "White"
},
{
Id: 2222222,
OptionName: "Size",
VariantName: "XL",
},
{
Id: 3333333,
OptionName: "Color",
VariantName: "GREEN"
},
{
Id: 4444444,
OptionName: "Size",
VariantName: "L",
}
];
const colors = arr.filter(it => it.OptionName == "Color");
const sizes = arr.filter(it => it.OptionName == "Size");
let results = [];
for(let color of colors)
{
for(let size of sizes)
{
results.push({Id: `${color.Id}_${size.Id}`});
}
}
console.log(results);
This question already has answers here:
Remove array element based on object property
(12 answers)
javascript - remove array element on condition
(11 answers)
Closed 1 year ago.
array, foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
and here's what I tried,
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
function removeRed(food) {
food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
return foods;
When I call the function like " removeRed(foods) " the output is giving both of the property-value pairs in my array.
I'm a beginner student and this is my first Question here. Hope that someone answers :'D
}
Put return inside the function before the filter called
function removeRed(food) {
return food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
}
Call the function to execute the code
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
removeRed(foods); // [{name: 'Egg', color: 'white'}]
Best practice Make always the function more generic like this:
function remove(food, color) {
return food.filter(function (x) {
if (x.color !== color) {
return true;
} else {
return false;
}
});
}
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
remove(foods,'white'); // [{name: 'Apple', color: 'red'}]
One line with ES6+ syntax:
const remove = (food, color) => food.filter(x=> x.color !== color);
you need to return the output of the filter. you were returning the original array
function removeRed(food) {
return food.filter(function (x) {
if (x.color !== 'red') {
return true;
} else {
return false;
}
});
Use this code to filter non-red items
let foods = [{ name: 'Apple', color: 'red' }, { name: 'Egg', color: 'white' }];
const filtered = foods.filter(item => item.color !== 'red');
console.log(filtered)
I have a list of objects like this:
let colors = [
{
id: 0,
color: "green",
},
{
id: 1,
color: "blue",
},
{
id: 2,
color: "orange",
},
];
What is the best way (most optimized) to get an element with id=1... is there a way to do it without iterating through the list?
Small tip:
Use const instead of let when you're not reassigning values
Try doing the following:
// ✅ good pattern: destructuring. We only use what we need
const myColor = colors.find(({ id }) => id === 1)
You can iterate over the whole array once and create a lookup table if the array is static. Then, lookups can be done in constant time after O(n) preprocessing.
let colors = [
{
id: 0,
color: "green",
},
{
id: 1,
color: "blue",
},
{
id: 2,
color: "orange",
},
];
const lookup = colors.reduce((acc,curr)=>(acc[curr.id] = curr, acc), {});
console.log(lookup[1]);
console.log(lookup[2]);
I have some data samples stored in a variable data_ as below.
[{'Age': 39, 'count': 5}, {'Age': 24, 'count': 5}]
So I have this javascript list as below:
barChartData(data) {
const datum = [
{
values: [
{
label: "A",
value: -29.765957771107,
color: "#3ebfea",
},
],
},
];
return datum;
}
// and use it
barChartData(data_) // passing the data sample to the function
And now what I want to do is, change the keys in the datum inside function with the data_ I pass.
so it will look like this:
barChartData(data) {
const datum = [
{
values: [
{
label: "Age",
value: <Age-received-from-data-parameter>,
color: "#3ebfea",
},
],
},
];
return datum;
}
How can I iterate/map the data inside the barChartData function and assign the value
I tried but I it is not working and I am pretty sure something is missing.
Can someone help me do this?
This is I what I tried
barChartData(data) {
const datum = [
{
// key: "Cumulative Return",
values: [
data.map((emp, index) =>
{ // below gives syntax errors
label: "Age",
value: emp.Age,
color: "#3ebfea",
}
)
],
},
];
return datum;
}
First, map function already returns an array, and it seems there's no need to wrap it into [] once more. Second, when arrow function returns an object, it should be wrapped into () to avoid confusing the parser. So here's one way your function might look like:
const source = [{
'Age': 39,
'count': 5
}, {
'Age': 24,
'count': 5
}];
// ----------------
function barChartData(data) {
const datum = [{
// key: "Cumulative Return",
values: data.map(emp => ({ // note `(` wrapper
label: "Age",
value: emp.Age,
color: "#3ebfea",
}))
}];
return datum;
}
console.log(barChartData(source));
I've got an array of nested objects
var arr = [{
tires: 2,
exterior: {
color: 'white',
length: 2,
width: 1
}
},{
tires: 4,
exterior: {
color: 'blue',
length: 5,
width: 3
}
},{
tires: 4,
exterior: {
color: 'white',
length: 2,
width: 3
}
}];
I want to create a function such that:
var findItems = function(arr, value){
// return array of found items
};
Some examples:
findItems(arr, 'white'); // [ arr[0], arr[2] ]
findItems(arr, 2); // [ arr[0], arr[2] ]
findItems(arr, {tires: 2}); // [ arr[0] ]
findItems(arr, {tires: 2, color: 'white'}); // [ ]
findItems(arr, {width: 1, color: 'white'}); // [ arr[0] ]
It's easy enough to find values for arrays with non-nested objects or if you know the exact level that you want to search in. But I'm not sure how to go about just finding "any value, anywhere" in an array. I quickly get into looping hell.
I can use Underscore if that helps.
I think it would be something like this:
function isObject(val) {
return Object(val) === val;
}
function search(val, ctx) {
var valIsObject = isObject(val);
return (function search(context) {
if(!isObject(context)) return val === context;
if(valIsObject && Object.keys(val).every(function(key) {
return context[key] === val[key];
})) return true;
return Object.keys(context).some(function(key) {
return search(context[key]);
});
})(ctx);
}
function findItems(arr, value){
return arr.filter(function(item) {
return search(value, item);
});
}
It should work reasonably well, except in some edge cases like circular references (infinite recursion) or descriptor properties (the code may call the getter on an incompatible object).