Extract first number - javascript

how can i extract the first number from this array?
The number is taken from the variable and then divided, from 0222 to [ 0, 2, 2, 2 ]
I need to check the first number, but I can't.
thank you
var cellF9 = sh.getRange(9, 6, 1, 1).getValue();
String(cellF9).split("").map(Number);
function splitNum(num) {
return String(num).split("").map(Number);
}
console.log(splitNum(cellF9));
switch (cellF9[0]) {
case 0:
sh.getRange("F18").setValue("test");
break;
default:
SpreadsheetApp.getUi().alert(".......", ".............", SpreadsheetApp.getUi().ButtonSet.OK);
}

In switch (cellF9[0]) { you are indexing against the original string "0222". You can either do
switch (splitNum(cellF9[0])) {
or
const splittedNumber = splitNum(cellF9[0])
switch (splittedNumber) {
A solution without splitting it into an array:
const cell = '0222'
console.log(cell.charAt(0))

let array = [1,2,3,4]
const firstElement = array[0]
Have you tried just accessing it?

solved thanks :)
var arrayf9=splitNum(cellF9);
switch (arrayf9[0]) {
..........
..........

Related

Dynamically create array of objects, from array of objects, sorted by an object property

I'm trying to match and group objects, based on a property on each object, and put them in their own array that I can use to sort later for some selection criteria. The sort method isn't an option for me, because I need to sort for 4 different values of the property.
How can I dynamically create separate arrays for the objects who have a matching property?
For example, I can do this if I know that the form.RatingNumber will be 1, 2, 3, or 4:
var ratingNumOne = [],
ratingNumTwo,
ratingNumThree,
ratingNumFour;
forms.forEach(function(form) {
if (form.RatingNumber === 1){
ratingNumOne.push(form);
} else if (form.RatingNumber === 2){
ratingNumTwo.push(form)
} //and so on...
});
The problem is that the form.RatingNumber property could be any number, so hard-coding 1,2,3,4 will not work.
How can I group the forms dynamically, by each RatingNumber?
try to use reduce function, something like this:
forms.reduce((result, form) => {
result[form.RatingNumber] = result[form.RatingNumber] || []
result[form.RatingNumber].push(form)
}
,{})
the result would be object, with each of the keys is the rating number and the values is the forms with this rating number.
that would be dynamic for any count of rating number
You could use an object and take form.RatingNumber as key.
If you have zero based values without gaps, you could use an array instead of an object.
var ratingNumOne = [],
ratingNumTwo = [],
ratingNumThree = [],
ratingNumFour = [],
ratings = { 1: ratingNumOne, 2: ratingNumTwo, 3: ratingNumThree, 4: ratingNumFour };
// usage
ratings[form.RatingNumber].push(form);
try this its a work arround:
forms.forEach(form => {
if (!window['ratingNumber' + form.RatingNumber]) window['ratingNumber' + form.RatingNumber] = [];
window['ratingNumber' + form.RatingNumber].push(form);
});
this will create the variables automaticly. In the end it will look like this:
ratingNumber1 = [form, form, form];
ratingNumber2 = [form, form];
ratingNumber100 = [form];
but to notice ratingNumber3 (for example) could also be undefined.
Just to have it said, your solution makes no sense but this version works at least.
It does not matter what numbers you are getting with RatingNumber, just use it as index. The result will be an object with the RatingNumber as indexes and an array of object that have that RatingNumber as value.
//example input
var forms = [{RatingNumber:5 }, {RatingNumber:6}, {RatingNumber:78}, {RatingNumber:6}];
var results = {};
$.each(forms, function(i, form){
if(!results[form.RatingNumber])
results[form.RatingNumber]=[];
results[form.RatingNumber].push(form);
});
console.log(results);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
HIH
// Example input data
let forms = [{RatingNumber: 1}, {RatingNumber: 4}, {RatingNumber: 2}, {RatingNumber: 1}],
result = [];
forms.forEach(form => {
result[form.RatingNumber]
? result[form.RatingNumber].push(form)
: result[form.RatingNumber] = [form];
});
// Now `result` have all information. Next can do something else..
let getResult = index => {
let res = result[index] || [];
// Write your code here. For example VVVVV
console.log(`Rating ${index}: ${res.length} count`)
console.log(res)
}
getResult(1)
getResult(2)
getResult(3)
getResult(4)
Try to create an object with the "RatingNumber" as property:
rating = {};
forms.forEach(function(form) {
if( !rating[form.RatingNumber] ){
rating[form.RatingNumber] = []
}
rating[form.RatingNumber].push( form )
})

Get the first value from a nested object

I have an object called allInvalidFields which lists invalid fields under an identifier e.g _0 or _3
The object could look like this
allInvalidFields = {
"_0" : {
0: input.foo,
1: select.la
}
"_1" : {
0: input.foofoo,
1: select.lala
}
}
But equally it could not have _0 as the first key and could look like this:
allInvalidFields = {
"_1" : {
0: input.alice,
1: select.bob
}
"_3" : {
0: input.foo
}
}
How can I get the first value from the first object in the list? So in the example above it would be input.foo or input.alice depending on which dataset was being searched.
Inferred that the keys are in numeric order and prepended with "_".
Under these assumptions :
function first(obj,n){
let smallest = Infinity;
for(i in obj){
console.log(i);
let val='';
if (i.toString()[0]=='_'){
val = parseInt(i.toString().substring(1));
}else{
val = i;
}
if( val < smallest ){
smallest = val;
}
}
if(n>0){
return first(obj["_"+smallest],n-1);
}
return obj[smallest];
}
first({"_0" : {
0: "input.foo",
1: "select.la"
},
"_1" : {
0: "input.foofoo",
1: "select.lala"
}},1); // input.foo
You need something like this.
var allInvalidFields = {
"_0": {
"0": "input.foo",
"1": "select.la"
},
"_1": {
"0": "input.foofoo",
"1": "select.lala"
}
};
var firstInput = Object.keys(allInvalidFields)[0];
console.log(allInvalidFields[firstInput][0]);
Object.values(allInvalidFields)[0][0];
take the first value of the first property object.
Small note: having such keys like _1 is bad style...
Short version of programaths answer:
allInvalidFields["_"+Object.keys(allInvalidFields).map(el=>el=+el.replace("_","")).sort()[0]][0]

How to sort data and measure the length as per key value using Javascript

I need one help.I have some array of data i need to sort the as per key value and measure the length.I am explaining my code below.
var response = [{
day_id:1,
day_name:"Monday",
subcat_id:"2",
cat_id:"1",
comment:"hii"
}, {
day_id:1,
day_name:"Monday",
subcat_id:"1",
cat_id:"2",
comment:"hello"
}
{
day_id:2,
day_name:"Tuesday",
subcat_id:"3",
cat_id:"2",
comment:"hii"
}]
Here for day_id=1 there are two set of data and same for day_id=2 present.I need to measure length of data set present as per day_id e,g.for day_id=1 length is 2Please help me.
You can map response and save in an object how many times each id was seen:
var counter = {};
response.map(function(item) {
counter[item.day_id] = (counter[item.day_id] || 0) + 1;
});
Your results are in counter:
console.log(counter);
// { '1': 2, '2': 1 }
Hope it helps.
Do not use .map, use .forEach as it doesn't return another array
and the code could be a little cleaner:
var counter = {};
response.forEach(function(item) {
counter[item.day_id] = ++counter[item.day_id] || 1;
});

lodash/underscore; compare two objects and remove duplicates

As you can see in the image below, I have some returned json data with three objects; each contains a clients id => data.
exact_match : {104}
match_4 : {104, 103}
match_2 : {104, 103, 68}
How can I "trim" or remove the duplicate objects based on previous ones? something like:
exact_match : {104}
match_4 : {103}
match_2 : {68}
I tried _.difference but did not work (Maybe because it is for arrays not objects?):
var exact_match = data.exact_match,
match_four_digits = _.difference(data.match_4, data.exact_match),
match_two_digits = _.difference(data.match_2, data.exact_match, data.match_4),
Any help would be appreciated :)
Update
I need that the returned value has the same object data instead of a new array :)
It looks like you want to diff keys (or rather, it'd be efficient to — _.keys)
_.difference(
_.keys({104: 1, 102: 3, 101: 0}), // ["104", "102", "101"]
_.keys({104: 1, 102: 3}) // ["104", "102"]
)
// [ "101" ]
Or, you could always convert your object to an array of pairs if you want to compare within the objects too (_.pairs):
_.difference(
_.pairs({104: 1, 102: 3, 101: 0}), // [["104",1], ["102",3], ["101",0]]
_.pairs({104: 1, 102: 2}) // [["104",1], ["102",2]]
)
// [["102", 3], ["101", 0]]
I would create a map called unique, e.g. var unique = {}; and then iterate over each key in your data and check if it's in unique. If it is in unique, delete the entry associated with that key, thus removing duplicates.
You could pull this check out as an alreadyFound method:
var alreadyFound = function (key) {
if (!(key in unique)) {
unique[key] = true;
return false;
}
return true;
};
Then iterate over your data and check alreadyFound(key) for key in your data, and delete the key if alreadyFound(key) returns true.
You could go messing with lodash/underscore methods but those might be inefficient depending on how you use them (and how they're implemented) and this should operate in linear time.
It looks like for your specific use case the full solution would be something like:
var unique = {};
// Assume I copy and pasted alreadyFound here
var alreadyFound = ...;
for (var object in data) {
// Iterate through ids in each object in data
for (var id in object) {
// Remove this entry if it's already found
if (alreadyFound(id)) {
delete object[id];
}
}
}
Thanks guys for the answers, I really appreciate your time.
I searched further and found this post by Lodash developer that helped me came up with this snippet;
var data = {
exact_match: {
104: {
supplier_id: 104
}
},
match_four_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
}
},
match_two_digits: {
104: {
supplier_id: 104
},
68: {
supplier_id: 68
},
103: {
supplier_id: 103
},
999: {
supplier_id: 999
}
}
};
var arr_match_four_digits = _.difference(_.keys(data.match_four_digits), _.keys(data.exact_match));
var arr_match_two_digits = _.difference(_.keys(data.match_two_digits), _.keys(data.match_four_digits), _.keys(data.exact_match));
$('#output1').html(JSON.stringify(data));
$('#output2').html(JSON.stringify(_.pick(data.match_four_digits, arr_match_four_digits)));
$('#output3').html(JSON.stringify(_.pick(data.match_two_digits, arr_match_two_digits)));
<script src="https://cdn.rawgit.com/lodash/lodash/3.3.1/lodash.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
data
<pre><code><div id="output1"></div></code></pre>
arr_match_four_digits
<pre><code><div id="output2"></div></code></pre>
match_two_digits
<pre><code><div id="output3"></div></code></pre>

Javascript, check multiple arrays for number

I'm looking for the best solution here, i've got an idea but thinking it could be done prettier.
I'm making an simple weather application. And i'm using Yahoo Weather api were they have got codes for weather conditions.
Depending on the condition i'm giving a code. Now, there are 50 codes and i've categorised them into 5 categories. In my case ex. my categori Snow contains 15 of Yahoo's condition codes.
Well, if you got a better idea (which i bet there is) be free to suggest.
My thought is to return the matching value from a set of arrays, but not shure how to do it.
My code now looks like this:
function getCondition(code) {
var snow = [1, 2, 3],
sun = [4, 5, 6];
}
What i need is the variable name that contains the matching number of the code?
I've made a JS-Fiddle
http://jsfiddle.net/BH8r6/
The fastest lookup (translating a Yahoo code to your label) is to use the code as array key (if they are sequential).
var weather = [];
weather[0] = "no_weather";
weather[1] = "snow";
weather[2] = "snow";
weather[3] = "snow";
weather[4] = "sun";
weather[5] = "sun";
weather[6] = "sun";
function getCondition(code) {
return weather[code];
}
Why dont you try an associative array when your key is your variable name and your values is the corresponding code for the variable name, thus your code will be something like this:
var myCodeArray=[];
myCodeArray["snow"]=[1, 2, 3];
myCodeArray["sun"] = [4, 5, 6];
now your method getCondition will be
function getCondition(code)
{
for(var definedCodeName in myCodeArray)
{
if(myCodeArray.hasOwnProperty(definedCodeName))
{
var array=myCodeArray[definedCodeName ];
for(var i=0;i<array.length;i++)
{
if(array[i]==code){
return definedCodeName ;}
}
}
}
return "Not found";
}
Demo
Why to complicate everything?! Just use 'switch' :
function getCondition(code) {
switch( code ){
case 1:
case 2:
case 4:
case 6:
return "snow";
case 3:
case 8:
case 9:
return "sun";
case 5:
case 7:
case 10:
return "cloudy";
}
return "none";
}

Categories