Given a JavaScript array, how to loop through and find a value? - javascript

I have a JavaScript array like so:
const colors = ['blue', 'red', 'green'];
Given a number from 0 to Infinity, how can I find a color value like so:
colors[0] === 'blue';
colors[1] === 'red';
colors[2] === 'green';
colors[3] === 'blue';
colors[4] === 'red';
colors[5] === 'green';
// …
After the array is exhausted, finding colors based on a numerical value should loop through the array in order.

Given any number "x" between 0 and infinity:
colors[x % colors.length]
Will get you one of your colours

Seems like a fairly easy task to accomplish, all you have to do is to use modulo % operator when looking for a given index, as follows:
const colors = ['blue', 'red', 'green', 'pink', 'black', 'white', 'anyother'];
function getColor(idx){
return colors[idx % colors.length]
}
getColor(0) // "blue"
getColor(7) // "blue"
getColor(8) // "red"
getColor(13) // "anyother"
getColor(14) // "blue"
getColor(21) // "blue"
This way your array will stay intact and you won't get index higher than your array length.

Use the remainder (%) operator. This will give you the remainder of a division.
1/3 = 0 Remainder 3
1%3 = 3
12/3 = 4 Remainder 0
12%3 = 0
if num % 3 == 0
color = 'blue';
if num % 3 == 1
color = 'red';
if num % 3 == 2
color = 'green';

Related

Can not complete codewar task: "Which color is the brightest?"

DESCRIPTION for a task:
One of the common ways of representing color is the RGB color model, in which the Red, Green, and Blue primary colors of light are added together in various ways to reproduce a broad array of colors.
One of the ways to determine brightness of a color is to find the value V of the alternative HSV (Hue, Saturation, Value) color model. Value is defined as the largest component of a color:
V = max(R,G,B)
You are given a list of colors in 6-digit hexidecimal notation #RRGGBB. Return the brightest of these colors!
For example,
brightest(["#001000", "#000000"]) == "#001000"
brightest(["#ABCDEF", "#123456"]) == "#ABCDEF"
If there are multiple brightest colors, return the first one:
brightest(["#00FF00", "#FFFF00", "#01130F"]) == "#00FF00"
Note that both input and output should use upper case for characters A, B, C, D, E, F.
My solution:
function brightest(colors){
let colorIndex = 0,
maxValue = 0
for (let i = 0; i < colors.lenght; i++) {
let color = colors[i],
r = ParseInt(color.slise(1,3), 16),
g = ParseInt(color.slise(3,5), 16),
b = ParseInt(color.slise(5,7), 16),
value = Math.max(r,g,b)
if (value > maxValue) {
maxValue = value
colorIndex = i
}
}
return colors [colorIndex]
}
Result:
Test failed with colors = #CAA365,#1861D3,#E8E2C6,#3D3548,#F19BBF,#BF12C3: expected '#CAA365' to deeply equal '#F19BBF'
What is wrong? And how can I fix this?
declare a variable
let value = Math.max(r,g,b)
length not lenght
let/var to variables
parseInt not ParseInt
slice not slise
And all will working

(JAVASCRIPT) Not updating my background color?

I'm trying to do a project for my CS assignment, but for some reason, it refuses to run the code correctly.
shake();
if (answers == 0 || 2 || 3 || 5) {
setProperty("screen1", "background-color", "green");
} else if (answers == 1 || 4) {
setProperty("screen1", "background-color", "red");
} else {
}
I set already set 'answers' to var answers = 0 and the shake function basically just randomizes a number for answers. However, even if answers == 1 or answers == 4, it still shows the background screen being green, not red. Any help?
Two solutions here worth exploring. One is to use a switch statement which is generally going to be the fastest:
function screenBg(answer) {
switch (answer) {
case 0:
case 2:
case 3:
case 5:
return 'green';
case 1:
case 4:
return 'red';
}
// In action:
setProperty("screen1", "background-color", screenBg(answers));
It can be a little weird to see a fall-through style of switch, which is why a look-up table is a good alternative:
const SCREEN_BG = [
'green', // 0
'red', // 1
'green', // 2
'green', // 3
'red', // 4
'green' // 5
];
setProperty("screen1", "background-color", SCREEN_BG[answers]);
Where here the correlation between index and colour should be pretty clear.
do it like this
shake();
if ([0,2,3,5].includes(answers)) {
setProperty("screen1", "background-color", "green");
} else if ([1,4].includes(answers)) {
setProperty("screen1", "background-color", "red");
} else {
}
the way your testing your if statement is wrong,
it should be like this:
if(answers === 0 || answers === 2 || ...)
Your conditions are incorrect and code can be improved a little bit.
let color = [0, 2, 3, 5].includes(answers)
? 'green'
: [1, 4].includes(answers)
? 'red'
: 'orange';
setProperty("screen1", "background-color", color);
If you prefer to use if-elseif-else
let color = "orange"; // this is for else block.
if ([0, 2, 3, 5].includes(answers)) color = "red";
if ([1, 4].includes(answers)) color = "green";
If "answers" is an array, use the condition like this:
[0, 2, 3, 5].some((x) => answers.includes(x))

How to change color for the numbers based on its value using javascript and react?

i want to apply colors to variable count based on its value using javascript.
what i am trying to do?
The value of variable count is dynamic it can have values below 0 or greater than 0.
so now when the count value is
0 color should be red
1 color should be yellow
greater than 1 color should be green
less than 0 meaning negative integers like -1, -2 so on color should be grey
I have the code below which changes color based on value.
const countColor = (count: number) => {
const colors = [red, yellow];
return colors[count] || green;
};
So the above code works for count values being 0 , 1 and value greater than 1. how do i change the above code such that it handles or changes count value to grey color when value is less than 0
Could someone help me fix this. thanks.
A simple way is to forget the [red, yellow] array and just process count to return the color:
const countColor = (count: number) => {
if (count < 0) return grey;
else if (count > 1) return green;
else if (count === 0) return red;
else if (count === 1) return yellow;
};
use terrnary operator that returns grey if count is less than zero otherwise returns colors[count] or green if colors[count] is undefined
const countColor = (count: number) => {
const colors = ['red', 'yellow'];
return count < 0 ? 'grey' : (colors[count] || 'green');
};

JavaScript string count loop misunderstanding

I am having trouble with a basic task. I need to write a JavaScript program that contains an array of at least five strings, loops through the array, and calls a function for each item; this function should check to see how long the string is:
If the string is less than four characters, print the phrase "Less Than Four"
If equal to four characters, print "Exactly Four"
If longer than four, print "More Than Four"
I have tried so many things, but feel like I am looking in the wrong spots. I understand this is basic but I cant seem to wrap my head around this...
My Code right now:
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
}
if (colors > 4) {
console.log("greater than 4");
}
if (colors < 4) {
console.log("less than 4");
}
if (colors = 4) {
console.log("is equal to 4");
}
Arrays have built-in methods for looping that allow a callback function to be executed upon each iteration of the loop. In your scenario, since you are just needing to examine the string, the .forEach() method is probably the most appropriate.
In the function, you only need a simple if/then/else statement to determine which message to print.
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(color){
if(color.length < 4){
console.log(color + " has less than 4 characters.");
} else if (color.length === 4) {
console.log(color + " has 4 characters.");
} else {
console.log(color + " has more than 4 characters.");
}
});
Newer versions of JavaScript support for..of syntax
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
for (const c of colors)
{ if (c.length > 4)
console.log(c, "greater than 4")
else if (c.length < 4)
console.log(c, "less than 4")
else
console.log(c, "equal to 4")
}
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
You should separate the concerns of the loop and the length check using a function -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
return "greater than 4"
else if (str.length < 4)
return "less than 4"
else
return "equal to 4"
}
for (const c of colors)
console.log(c, checkLength(c))
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript is a multi-paradigm language, so it supports writing the same program in a wide variety of styles -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = str =>
{ if (str.length > 4)
console.log(`${str} is greater than 4`)
else if (str.length < 4)
console.log(`${str} is less than 4`)
else
console.log(`${str} is equal to 4`)
}
colors.forEach(checkLength)
// teal equal to 4
// violet greater than 4
// silver greater than 4
// green greater than 4
// red less than 4
// purple greater than 4
JavaScript support for expressions is quite good too, removing the need for imperative-style keywords like if, else, switch, for, while, do and even return -
const colors =
[ "teal", "violet", "silver", "green", "red", "purple" ]
const checkLength = x =>
x.length > 4 // if ...
? `${x} is greater than 4`
: x.length < 4 // else if ...
? `${x} is less than 4`
: `${x} is equal to 4` // else
console.log(colors.map(checkLength))
// [ "teal is equal to 4"
// , "violet is greater than 4"
// , "silver is greater than 4"
// , "green is greater than 4"
// , "red is less than 4"
// , "purple is greater than 4"
// ]
Call a function on every element and check the length inside an if-else block
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
var count;
for (count = 0; count < colors.length; count++) {
console.log(colors[count]);
stringLength(colors[count]);
}
function stringLength(string) {
if (string.length > 4) {
console.log("greater than 4");
} else if (string.length < 4) {
console.log("less than 4");
} else {
console.log("is equal to 4");
}
}
You need to put the if statements inside the curly braces of the for loop, so for every color it will run through all the if conditions and print if it matches.
A more idiomatic way of doing what you're currently trying to do is to implement the logic within the body of a forEach function, which is part of the Array object's prototype
var colors = ["teal", "violet", "silver", "green", "red", "purple"];
colors.forEach(function(currentColorToCheck) { //currentColorToCheck is a temporary variable that the forEach function gives you (1 for every item of colors Array)
if (currentColorToCheck.length > 4) { // we use the .length function (part of String prototype and Array prototype) to get the length of the string
console.log("greater than 4");
}
if (currentColorToCheck.length < 4) {
console.log("less than 4");
}
if (currentColorToCheck.length === 4) { // here for an equality comparison, use === instead of =
console.log("is equal to 4");
}
})
The forEach is a more convenient way to express "Iterate over values of an Array". You can look at the documentation for some further guidance.
As a sidenote, there's tons of prototype (builtin) functions for every JavaScript type (Object, Array, String, Number, Date, Math, etc.) which you might want to study in your spare time. Mozilla Developer Network has great resources for that.

Finding the decimal exponent based on the index of a for-loop

The user chooses a number and then d3.js should display as many circles.
I have an array that is used to assigned color to the circles:
var color =["red","blue", "yellow", "orange",....., ]
● If the user choose 593, the first 500 circle should be red (color[0]) , the next 90 should be blue (color[1]) and the last 3 (color[2]) should be yellow Because
593= 500+90+3 = 5*10^2+9*10^1+3*10^0
or
with
var number = 593
var number_as_array = number.toString().split('');
Then
593 = 5*number_as_array[0]*10^number_as_array.length-0-1 + 9*number_as_array[1]*10^number_as_array.length-1-1+ 3*number_as_array[2]*10^number_as_array.length-2-1
● If the user choose 4168 the first 4000 circle should be red, the next 100 should be blue, the next 60 yellow and the last 8 orange
To assign the color to each circle I use to create an array of JS object build with a for loop
var data=[]
for (index =0; index< number; index++){
circle= {};
circle.cx = circle_x;
circle.cy = circle_y;
circle.color = color[????]
data.push(circle);
How can I assign the color to circle.color based on the condition above ?
Not to diminish from the other answer, here's an alternative approach.
Taking a given total number of circles, it checks to see how many significant digits of the total are required (rounding down) so that any given index is less than rounded total.
I'm not sure if that makes complete sense, so I'll use an example:
If there are 132 circles in total:
Indexes 0 through 99 will be less than 100 (132 rounded down with one significant digit).
Indexes 100 through 129 will be less than 130 (132 rounded down with two significant digits).
Indexes 130 and 131 will be less than 132 (132 with all significant digits).
Here's a quick demonstration (rows are 50 circles across):
var svg = d3.select("body")
.append("svg")
.attr("width",510)
.attr("height",510);
var n = 377;
var color = d3.scaleOrdinal()
.range(["steelblue","orange","crimson","lawngreen","pink"])
var digits = Math.floor(Math.log10(n));
var circles = svg.selectAll("circle")
.data(d3.range(n))
.enter()
.append("circle")
.attr("cx",function(d,i) { return i%50 * 10 + 5 })
.attr("cy",function(d,i) { return Math.floor(i/50) * 10 + 5 })
.attr("r",5)
.attr("fill", function(d,i) {
var exp = digits;
while (i < Math.floor(n/Math.pow(10,digits-exp))*Math.pow(10,digits-exp)) {
exp--;
}
return color(exp);
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/4.10.0/d3.min.js"></script>
var color = ["red","orange", "yellow", "green", "blue", "indigo", "violet"];
var circleCount = "4192"; // use string
var length = circleCount.length;
var counter = [];
for (var i = 0; i < length; i++) {
var digit = circleCount.substring(i, i+1);
var exponent = length - i - 1;
var number = digit * Math.pow(10, exponent);
counter.push(number); // might have to use .unshift instead of .push
}
console.log(counter);
for (var i = 0; i < counter.length; i++) {
for (var j = 0; j < counter[i]; j++) {
drawCircle(color[i]);
}
}
This is a perfect case for using D3's Threshold Scales: you give it N numbers where you want breaks between the colors, and N+1 colors to return for any input value. Here is the example from the docs:
var color = d3.scaleThreshold()
.domain([0, 1])
.range(["red", "white", "green"]);
color(-1); // "red"
color(0); // "white"
color(0.5); // "white"
color(1); // "green"
color(1000); // "green"
So the challenge for your case is how to convert (for instance) your example input of 593 into the array of the two numbers [500, 590]:
var sinput = 593 + ""; // make the input a string
var digits = sinput.split("").slice(0, -1); // use all digits but the last one
var breaks = digits.map((d, i, a) =>
+(a.slice(0, i+1).join("")) * Math.pow(10, a.length-i)
);
var colors = ["red", "blue", "yellow", "orange"];
var tScale = d3.scaleThreshold()
.domain(breaks)
.range(colors);
Anything < 500 maps to "red", from 500 - 589 maps to "blue", and ≥ 590 maps to "yellow". The additional range color ("orange") is not used, unless a 4-digit number is used as input.
Note: this logic assumes the input number will have at least 2-digits.
You can now assign the color at the time of creating the circle -- rather than pre-populating it in the data array -- using syntax like .attr("color", (d, i) => tScale(i))
The other approaches seem overly complex. You can split the number into its digits, then create the required 10^digitIndex circles with colour based on the index. I've included a line to check that the number isn't too big.
function mapColors(num) {
var color =['red','blue', 'yellow', 'orange'];
// If the number is longer than the color array, return undefined
if ((''+num).length > color.length) return;
return (''+num).split('').reduce(function (acc, n, i, arr) {
for (var j=n*Math.pow(10, arr.length-i-1); j; --j) {
acc.push({'color':color[i]});
// Add more circle properties here
}
return acc;
}, []);
}
console.log(mapColors(23));

Categories

Resources