JavaScript - Search for element in array that includes SOME of text - javascript

I am trying to find in an array includes SOME of the text in an element. Here is what I have:
['red', 'green', 'blue'].some(e => e.includes('red:square')) // false
Which returns false. But I would like it to return true because obviously red is inside one of the elements of the array.

You can use Alternation ( | ) and Search function
console.log(['red', 'green', 'blue'].some(e => e.search(/red|square/)))

console.log(['red', 'green', 'blue'].some(e => ['red','square'].includes(e))) //positive test case
console.log(['red', 'green', 'blue'].some(e => ['white','square'].includes(e))) //negative test case

Related

How do i search for a particular value from an array of objects?

I have an array of objects called 'Tags' of type :
type Tag = {
id: number,
label: string
}
Below is some sample data inside it.
const [tags, setTags] = useState<Tag[]>([{id: 1, label: "random"}, {id: 2, label: "important"}, {id: 3, label: "ignore"}])
I have an input field which takes input and sets it to "input" state on change.
I want to display a paragraph element only if the searched input field doesn't exist inside the tags.
I was unable to find a way to directly search it as the tags array is made of objects and i want to search that object's label property.
So i ended up doing something like this...
{tags.map(tag => {
if(!(tag.label.toLowerCase().includes(input.toLowerCase()))){
return <p>{input}</p>
}
})}
but this would render the paragraph each time the input doesn't match the values. So in this case it renders the paragraph 3 times if i add a new label. I want it to render just once. How do i fix this?
You could use filter to filter tags and then if result has a length > 0 show <p>{input}</p> one time:
return (
{tags.filter(tag => !(tag.label.toLowerCase().includes(input.toLowerCase())).length > 0 &&
<p>{input}</p>
})});
To render the input in a p tag when none of the labels includes it:
const Bla = () => { // assuming Bla is your component
const shouldRenderInput = tags.every(
(tag) => !tag.label.toLowerCase().includes(input.toLowerCase())
);
return <>{shouldRenderInput && <p>{input}</p>}</>;
};
see Array.prototype.every

How to make style property names to lowercase

so i have a object list for styles like this,
const styles = {
'font': 'font',
'fontSize': 'font-size',
'fontFamily': 'font-family',
'fontVariant': 'font-variant',
'fontWeight': 'font-weight',
'fontStyle': 'font-style',
'margin': 'margin',
};
<div style='MARGIN:10px; FLOAT:left'></div>
FYI-i'm using an editor so that when i paste the HTML code, sometimes it has those property names in UPPERCASE .
how to do i make sure that all the property names are lowercase what function/method should i use to check the case?
I think you need to combine what has been said already.
document.querySelectorAll('p').forEach(p => {
p.setAttribute('style', p.getAttribute('style').toLowerCase())
console.log(p)
})
<p style="COLOR: red;">Foo</p>
<p style="COLOR: blue;">Bar</p>
<p style="COLOR: green;">Baz</p>
That said, I wouldn't do it at runtime. Maybe do it once and serve the transformed HTML directly to the user. Maybe even some automated setup with gulp or 11ty.
The style are also visible without transforming. (for me in chrome)
If you can use ES6, then you could create a new object using Object.entries:
const lowerCaseStyles = Object.entries(styles).map(([key, value]) => ({ [key.toLowerCase()]: value}));
If im not wrong, you wanted to check if the properties of the style attribute are UPPERCASED or lowercased
First of all, you can first get the value of the style attibute like
const value = document.querySelector("div").getAttribute("style");
//this will return 'MARGIN:10px; FLOAT:left'
then you can simply turn them to lowercase with toLowerCase
const lowercased = value.toLowerCase();
and then you can check if the properties with something like
return value === lowercased
<div style='margin:10px; float:left'></div> returns true
<div style='MARGIN:10px; FLOAT:left'></div> returns false

React (Material UI) - MakeStyles with switch

So I have a button thats suppose to change the backgroundcolor depending on a variable (props.status), which is an int.
I can understand that its possible to swap between two values e.g. using something like backgroundColor: props.status ? 'red' : 'blue', but what if I have many colors?
Kinda assumed something like this would work, but it doesn't.
backgroundColor: (() =>
{
switch (props.status)
{
case 0:
return 'red'
case 1:
return 'red'
default:
break;
}
})
You need to execute the function that you just declared:
(() => {
//...
})() // note the last pair of parentheses
This pattern is called IIFE

How can I insert sequential values from an array into another mapped array?

I'm fairly new to Javascript and I'm having issues with a component I'm playing with.
I have an array of data that I am successfully mapping into a component. I have another array that contains the visual properties I wish to pass in as props. For example, I'd like the first returned to be red, the next blue, the last green and then repeat the sequence. How might I do this?
I've had a crack at it but you will immediately see why my solution hasn't worked. I understand why this hasn't worked but I'm not sure what to try next.
Can anyone point me in the right direction?
const colorsList = ["red", 'blue', "green"]
console.log(colorsList)
const IndustriesPage = ({data}) => (
<Layout>
<HeroInternal
title="Industries"
/>
<GridBlock>
{data.allContentfulPageCaseStudy.edges.map(function(target){
return(
<TextLinkModule
linkTitle = {target.node.industry}
titleModifier = 'textLinkModule__title--small'
backgroundColor = {colorsList.map(function(target){
return(
target,
console.log(target)
)
}
)}
linkDestination = {`industries/${target.node.industry}`.split(' ').join('-').split('&').join('and').toLowerCase()}
// backgroundImage = {target.node.linkBackgroundImage.fluid.src}
/>
)
})
}
</GridBlock>
<ContactUsBlock></ContactUsBlock>
</Layout>
)
The map function returns the value and the index of each member of the array. You can use the index of each edge to return a single value from the colorsList array.
data.allContentfulPageCaseStudy.edges.map(function(target, idx){
...
backgroundColor = { colorsList[idx % colorsList.length] }

How to pass array using spread syntax into method in JavaScript

I am trying to pass an array into a method but having issues with quotes. Here is a case similar to what I am trying to achieve.
const remove = ['blue', 'round', 'tall']
function removeClass(param) {
foo.classList.remove(param)
}
removeClass(...remove)
The issue is that the result is foo.classList.remove('blue, round, tall') which won't work. I am trying to achieve this foo.classList.remove('blue', 'round', 'tall')
I have tried using remove.map(el => `'${el}'`).join(',') but then the result is foo.classList.remove("'blue', 'round', 'tall'") which also doesn't work.
Try using rest parameters:
const remove = ['blue', 'round', 'tall'];
function removeClass(...param) {
foo.classList.remove(...param);
}
removeClass(...remove);

Categories

Resources