How to return a string based on correspondent values summed from an array of strings

Images
Related searches

As the topic states what is the best way to make it so that when you pass an array of emotions/values, to show the closest value based on a numeric mapping in javascript?.

Assume that 'Glad' is the same thing as 'Happy', and 'Down' is the same thing as 'Sad'. Ithe code I've tried seems incredibly lengthy and gets bloated if I add more emotions/states (i.e. Angry). Aside from the emotions array, any new functions and data structures and variables can be changed/introduced.

for example, I can get a list of emotions:

let emotions = ['Happy','Happy','Sad','Glad','Angry']; 

Now I want to return a string that reflects what the 'closest' emotion based on these 5 emotions.

For a better example, let's assume the values correspondent to each emotion is:

Angry = 1, Happy = 2, Sad = 3

I was trying something like:

var numb = 0;
for (var i = 0; i < emotions.length; i++) {
  if (numb == 'Angry')
    numb += 1;
  if (numb == 'Happy' || numb == 'Glad')
    numb += 2;
  if (numb == 'Sad' || numb == 'Down')
    numb += 3;
}
var average = numb / emotions.length;

// check which number is closer to
if (average < 1.5)
  return 'Angry';
if (average >= 1.5 && < 2.5)
  return 'Happy';
if (average > 2.5)
  return 'Sad';
if (average == 1.5)
  return 'Angry or Happy';
if (average == 2.5)
  return 'Happy or Sad';

My expected result based on this list of emotions is: 2(*Happy*) + 2(*Happy*) + 3(*Sad*) + 2(*Happy|Glad*) + 1(*Angry*) = 10 Then divide by 5 (the emotions array length), resulting in 2. So the result that should be returned, as string, is "Happy".

Let's say I added a fourth type of emotion/feeling... I would be adding more and more of these conditions, and it gets more complicated in the logic checking for the ranges of the numbers.

I am looking at the list of emotions as a whole, and trying to come up with an overall emotion that represents the whole list.

What is the best way to do this so that the code looks clean and I can support more states without having the lines of code become too long?

What about something like this:

Having two object constants: emotionsValues: Here you assing a value to each emotion you want, like a score to each. emotionsRank: Here is the final result of each value, based on average you'll get the result from here.

Now:

  1. Receive the emotions array by parameter.

  2. reduce it based on the value of each mapped emotion (using emotionsValues).

  3. Get the average

  4. See if the floor value + ceil value divided by 2 is equal to the number itself (it means its exactly the half), so use the "emotion or emotion".

  5. OR, if not the half, then round to the nearest and get the correct emotion. Don't forget to check if average is below 1 or bigger the the last rank (3 in this case)

const emotionsValues = {
  "Angry": 1,
  "Happy": 2,
  "Glad": 2,
  "Sad": 3,
  "Down": 3,
}

const emotionsRank = {
  1: "Angry",
  2: "Happy",
  3: "Sad",
}

function getEmotion(arrayEmot) {
  let numb = arrayEmot.reduce((acc, v) => Number(emotionsValues[v]) + acc, 0);

  let avg = numb / arrayEmot.length;
  let min = Math.floor(avg)
  let max = Math.ceil(avg)

  if ((min + max) / 2 == avg && min != max) {
    return emotionsRank[min] + " or " + emotionsRank[max]
  } else {
    let rounded = avg < 1 ? 1 : avg > 3 ? 3 : Math.round(avg);    
    return emotionsRank[rounded];
  }
}

let emotionsTest = ['Happy', 'Happy', 'Sad', 'Glad', 'Angry'];
console.log(getEmotion(emotionsTest))

let emotionsTest2 = ['Happy', 'Happy', 'Sad', 'Sad'];
console.log(getEmotion(emotionsTest2))

Sum of the alphabetical values of the characters of a string , Remove odd frequency characters from the string � Sort the strings based on You are given an array of strings str, the task is to find the score of a given Then calculate the sum of the alphabetical values of the given string. int n = sizeof ( str) / sizeof (str[0]);. int score = strScore(str, s, n);. cout << score << endl;. return 0;. }� In this section we will see how to define an array of strings in C++. As we know that in C, there was no strings. We have to create strings using character array. So to make some array of strings, we have to make a 2-dimentional array of characters. Each rows are holding different strings in that matrix. In C++ there is a class called string.

Array methods, Here we can see that splice returns the array of removed elements: It's similar to a string method str.slice , but instead of substrings it It may contain numbers or strings or objects or whatever. They are used to calculate a single value based on the array. Here we get a sum of an array in one line:. To get INDEX to return an array of items to another function, you can use an obscure trick based on the IF and N functions. In the example shown, the formula in E5 is: =SUM(INDEX(data,N(IF(1,{1,2,3})))) where "data" is the named range B5:B10.

This function explicitly checks for the "mid" case and also for out of range values (since it's based on indices):

function getEmotion(emotions, value) {

  // Out of range
  if ( value > emotions.length ) return emotions[emotions.length - 1];
  if ( value < 1 ) return emotions[0];

  // Determine if decimal is .5
  let mid = value % 1 === .5;
  // Round the value to the nearest integer
  let rounded = Math.round(value);

  return mid ? `${emotions[rounded - 2]} or ${emotions[rounded - 1]}` : emotions[rounded - 1];

}

Output:

let emotions = ['Happy', 'Happy', 'Sad', 'Glad', 'Angry'];

console.log(getEmotion(emotions, -23));    // Happy
console.log(getEmotion(emotions, 0));      // Happy
console.log(getEmotion(emotions, 1));      // Happy
console.log(getEmotion(emotions, 2.43));   // Happy
console.log(getEmotion(emotions, 2.5));    // Happy or Sad
console.log(getEmotion(emotions, 3.1));    // Sad
console.log(getEmotion(emotions, 155.65)); // Angry

XPath and XQuery Functions and Operators 3.1, 17 Maps and Arrays The dynamic type of the value returned by the function is the same as its static type Subtype Substitution: A derived type may substitute for its base type. in this specification are always strings (single xs:string values) . Returns the arithmetic sum of its operands: ( $arg1 + $arg2 ). Therefore arrays of strings is an array of arrays of characters. Here, string array and arrays of strings both are same term. For Example, if you want to store the name of students of a class then you can use the arrays of strings. Arrays of strings can be one dimensional or multidimensional. Declaring the string array: There are two ways to

You could create a set of indices and get the values by filtering with the index.

function getEmotion(emotions, value) {
    var values = new Set([value + 0.5, value - 0.5, Math.round(value)]);
    return emotions.filter((e, i) => values.has(i + 1)).join(' and ');
}

console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1));
console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1.5));
console.log(getEmotion(['Happy', 'Sad', 'Glad', "Angry"], 1.7));

JavaScript Arrays reduce Method, A second (optional) argument to the reduce method is an initial value to provide as the The following examples use the reduce method to return the sum of the array element values. Using reduce Method to Convert Array of Arrays to String . The second and third arguments to INDEX are the numbers 3 and 1, which instruct INDEX to find the value in the third row and first column of the array and return it to the worksheet. You can enter the full INDEX formula as just given normally, with an array of LINEST results as its first argument, without the Ctrl and Shift and Enter

Ways to Loop Through JavaScript Arrays, This example modifies the array by multiplying each of its values times 2: var sum = 0; // to hold sum of numeric array values for (var i=0, len=ar.length; But if you want to create a new array based on values in the existing array, Notice that even though our function didn't return anything for values that are not strings, � Because creating a String array is just like creating and using any other Java object array, these examples also work as more generic object array examples. 1) Declaring a Java String array with an initial size. If you know up front how large your array needs to be, you can (a) declare a String array and (b) give it an initial size, like this:

Select VALUE in the list to bring up the function's dialog box. In the dialog box, select the Text line. Select cell A3 in the spreadsheet. Select OK to complete the function and return to the worksheet. The number 30 appears in cell B3. It is aligned on the right side of the cell to indicate it is now a value that can be used in calculations.

Output: 2 1 0 Method 3 (Hashing) We can use a hash map and insert all given strings into it. For every query string, we simply do a look-up in the hash map. Please refer Data Structure for Dictionary for comparison of hashing and Trie based solutions.

Comments
  • Math.round()?
  • @CalvinNunes That could be a part of it, but in my case I want it so that 1.5 would mean 'Happy or Sad' (the middle ground) and not just default to rounding up.
  • I kinda think this question might have a better home on codereview.stackexchange.com - you could check out their topic rules
  • Are you wanting to use the array index to get the string? You could strip the decimal (if not a whole number), then get emotions[x] + ' or ' + emotions[x + 1]
  • I think there's some confusion here. Is the user passing an array of emotions (strings) or an array of float values?
  • Is this accounting for the average of all emotions though? Like if there was overwhelming number of Angry's there... would this account for that? Looking at this, it seems like it just accounts for the min/max, but not the amount/number of each emotion. I am looking at the list of emotions as a whole, and trying to come up with an overall emotion that represents the whole list.
  • I think it is a little confusion to understand your goal and from where does the array of emotios come from... but no, it's only based on an average number, not based on array, now that you said, I finally understood your goal... I have little time now, but if I can, I would edit and try to answer what you really need
  • Can you post on your question, the values for all emotions, (1=happy, 2=sad,...)? And also, does emotions array be received by parameter? Can't you use the first part of your code, that checks the numb and average, then get this average and pass to my function of getEmotion, wont it result in your desired goal?
  • 1-Angry, 2-Happy, 3-Sad. It can be received by parameter. Yes, you can do that.
  • @Rolando I think that my edit do what you need, please review it