I want to create a function like this, but I want the variable name and colour to be properties of this function, which means I just have to give them value when construct the function and do not have to declare them each time I call the function.
function A(input) {
var name = ["USA", "Japan", "India"]; // make it properties
var color = ["blue", "red", "green"]; // make it properties
var index = name.indexOf(input);
return color[index];
}
To make it clear, let me show my ideal code like this:
function A(input) {
var index = this.name.indexOf(input);
return this.color[index];
}
A.name = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];
Is it possible to set the function some properties like object? Thanks
Finally the problem is solved by module pattern, please attach to the accepted answer.
A module pattern could do this, but it will make the properties private (I don't know if it's what you need):
var A = (function() {
var name = ["USA", "Japan", "India"];
var color = ["blue", "red", "green"];
return function(input) {
var index = name.indexOf(input);
return color[index];
};
})();
The easiest way you can do this via passing the values in the parameter.
function A(input, name, color) {
var index = name.indexOf(input);
return color[index];
}
//Can be called like this
A("USA", ["USA", "Japan", "India"], ["blue", "red", "green"]);
Alternatively you can pass an object to a then just get from it.
function A(objectInput) {
var input = objectInput.input ? objectInput.input : "",
name = objectInput.name objectInput.name : [],
color = objectInput.color ? objectInput.color : [],
index = name.indexOf(input);
return color[index];
}
//Called like this.
A({
input: "USA",
name: ["USA", "Japan", "India"],
color: ["blue", "red", "green"]
});
function A(input) {
var index = A.country.indexOf(input);
return A.color[index];
}
A.country = ["USA", "Japan", "India"];
A.color = ["blue", "red", "green"];
console.log(A("USA")); //Blue
Don't use name as property name, it returns function name by default.
Better code style:
function A(input) {
return A.colors[input];
}
A.colors = {
"USA": "blue",
"Japan": "red",
"India": "green"
}
Related
So suppose my array looks like this:
let langArr = [
["python", "blue"]
,["python", "blue"]
,["c++", "red"]
,["java", "yellow"]
,["javascript", "lime"]
,["shell", "green"]
,["c++", "red"]
];
what I want is something like this:
{
python: {
count: 2
color: "blue"
}
c++: {
count: 2
color: "red"
}
java: {
count: 1
color: "yellow"
}
and so on...
}
I tried reduce method like this:
let langCount = langArr.reduce((lang, [name, color]) => {
lang[name] = (lang[name] || 0) + 1;
lang[color] = 'color';
return lang;
}, {});
console.log(langCount);
but I get this output:
{
python: 2
blue: "color"
c++: 2
red: "color"
java: 1
yellow: "color"
and so on...
}
You need an object for each language.
This approach takes an object as default value if lang[name] is falsy, like undefined.
The pattern
variable = variable || value;
works with a logical OR ||:
if variable has a truthy value, take this value,
if variable has a falsy value, take value instead.
let langArr = [["python", "blue"], ["python", "blue"], ["c++", "red"], ["java", "yellow"], ["javascript", "lime"], ["shell", "green"], ["c++", "red"]],
langCount = langArr.reduce((lang, [name, color]) => {
lang[name] = lang[name] || { count: 0, color };
lang[name].count++;
return lang;
}, {});
console.log(langCount);
You can use this:
array.reduce((acc, current) => {
if(!acc.hasOwnProperty(current[0])){
acc[current[0]] = {count: 0, color: current[1]};
}
acc[current[0]].count += 1;
return acc;
}, {});
Having an object like:
var animals = { "dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]};
I want to get back the name of the animal which has a certain color, for example for "red" I want to return an array containing ["dog", "cat"];
Tried to do it but I only get back Array(0) or Array(1)
function findColor(animals, color) {
var result = [];
if (Object.values(animals).indexOf(color) > -1) {
result.push(color);
}
return result;
}
console.log(findColor(animals, "red"));
You can use simply use Object.keys and filter
var animals = {
"dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]
};
function findColor(animals, color) {
return Object.keys(animals).filter(key=>animals[key].includes(color))
}
console.log(findColor(animals, 'red'));
Why my code is not working ?
indexOf uses strict comparision, Object.values(animals) returns an 2d array and you're trying to match it with a string value, what you need to do it loop over keys and use indexOf on subarray on 2d array
var animals = {"dog": ["black", "red", "green"],"cat": ["pink", "red", "white"],"bird": ["green", "grey", "yellow"]};
function findColor(animals, color) {
var result = [];
Object.keys(animals).forEach(v => {
if (animals[v].indexOf(color) > -1) {
result.push(v)
}
})
return result;
}
console.log(findColor(animals, "red"));
You can use Object.keys and then iterate the array and then check based on condition :
var animals = { "dog": ["black", "red", "green"],
"cat": ["pink", "red", "white"],
"bird": ["green", "grey", "yellow"]};
function findColor(animals, color) {
let result = []
Object.keys(animals).forEach(key=>{
if(animals[key].indexOf(color)>-1){
result.push(key)
}
});
return result;
}
console.log(findColor(animals, "red"));
I have an array such as var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"]; and I would like to be able to loop through the array to create an object from each element.
var zoo = {
Dog : {
color: brown,
age: 4
},
Cat : {
color: black,
age: 12
I have found some solutions for defining the other properties with .keys and .values but I am stuck on how to name the object. Thanks for any help!
You can achieve the solution using Array.reduce.
reduce provides an elegant way to return desired output based on your array.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo=arr.reduce((zooObj, animal)=>
{
zooObj[animal] = {
color: 'black', //You can add color based on some logic here
age: 4 //You can add age based on some logic here
}
return zooObj
}, {})
console.log(zoo) //*Output*: { "Dog": { "color": "black", "age": 4 }, "Cat": { "color": "black", "age": 4 }, "Horse": { "color": "black", "age": 4 }, "Pig": { "color": "black", "age": 4 }, "Cow": { "color": "black", "age": 4 } }
You can try with below:
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["Red", "Blue", "Green", "Dark", "Yellow"];
var zoo={};
var i = 10;
var colorIndex = 0;
arr.forEach(v=>{
zoo[v]={};
zoo[v].age=i++;
zoo[v].color=colors[colorIndex++];
});
console.log(zoo);
You can simply do it in this way :
var objArr = {};
arr.forEach((data, index) => {
objArr[data] = data; //here you can add what ever value you want to add to that key
})
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var zoo = {};
for (var i of arr ){
zoo[i] = {};
zoo[i].age = 'age'; //fill the age
zoo[i].color= 'your favorite color'; //fill with your favorite color
}
console.log(zoo);
This will do-
var animal = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var color=["red","green","blue","orange","yellow"];
var age=[2,5,8,6,23];
var obj={};
animal.forEach((e)=>{
obj[e]={};
obj[e].age=age[animal.indexOf(e)];
obj[e].color=color[animal.indexOf(e)];
})
console.log(obj)
You can do this by using below logic.
Here define color and age array and inside loop store this dynamically.
var arr = ["Dog", "Cat", "Horse", "Pig", "Cow"];
var colors = ["brown","blak","white","red","gray"];
var ages = ["4","12","5","10","15"];
arr2 = {}
for(var i=0;i<arr.length;i++){
arr2[arr[i]] = {};
arr2[arr[i]].color = colors[i]; //fill the age
arr2[arr[i]].age= ages[i];
}
console.log(arr2);
https://jsfiddle.net/brahmpragya/w76xjm5y/29/
I thought my map and pluck functions are collection correct, but when I try to call pluck to get "type" of car object, it returns an empty array....? empty array...???
update: thanks for pointing out that it is object.....So I added for in in my map function, but seems not working? is anything wrong?
function map(collection,iterator){
var result=[];
if(Array.isArray(collection)){
for (var i=0;i<collection.length;i++){
result.push(iterator(collection[i]));
}
}else{
for (var key in collection){
result.push(iterator(collection[key]))};
}
return result;
};
function pluck(collection, key) {
return map(collection, function (value) {
return value[key]
});
}
var car = { type: "Fiat", model: "500", color: "white" };
console.log(pluck(car, function (auto) {
return auto.type;
}));
> the result: []
console.log(pluck(car, function (auto) {
return auto.type;
}));
should be
console.log(pluck(car, 'type'));
Also, car needs to be an array.
var car = [{ type: "Fiat", model: "500", color: "white" }];
You are passing this
var car = { type: "Fiat", model: "500", color: "white" };
While your map function expects array.
Use for-in loop if you want to pass object.
Pluck function only makes sense for arrays, because only arrays make sense to map. For objects you want to just read property:
var car = { type: "Fiat", model: "500", color: "white" };
console.log( car.type );
function map(collection, filter) {
var result = [];
for (var i = 0; i < collection.length; ++i) {
result.push(filter(collection[i]))
}
return result;
}
function pluck(collection, filter) {
return map(collection, filter);
}
var cars = [{type: "Fiat", model: "500", color: "white"}]
var result = pluck(cars, function(auto) {
return auto.type;
})
document.write(JSON.stringify(result))
because its an object, not array
I have an array with multiple objects
"status": [
{
"feature": "sun",
"color": "yellow",
},
{
"feature": "rain",
"color": "grey",
},
I want to return the value of the property 'color' for each 'feature'
The output would return: 'yellow' and 'grey'
I don't really know how to start ...
Thanks
use this:
for (var i = 0; i < yourObject.status.length; i++)
{
console.log(yourObject.status[i].color);
}
Maybe you should start at the beginning with how loops work?
You could use filter.
filter returns an array, so if you're sure that there will only be a 1:1 correlation between feature/color just return the color value of the first element:
function getColor(feature) {
return obj.status.filter(function (el) {
return el.feature === feature;
})[0].color;
}
getColor('sun'); // yellow
getColor('rain'); // grey
DEMO
Try this
var obj = {
// ...
"status": [
{
"feature": "sun",
"color": "yellow"
},
{
"feature": "rain",
"color": "grey"
}
]
// ...
}
// Array
var r1 = obj.status.map(function(obj) {return obj.color})
// String
var r2 = obj.status.map(function(obj) {return obj.color}).join(' ')
console.log(r1, r2)