Computing Share Of Wallet Using JavaScript

From Q
(Redirected from Computing Share of Wallet)
Jump to navigation Jump to search

Consider a situation where you want to compute a share of wallet measure for each respondent, based on the number of products that a customer holds where the products’ holdings are in four variables q1c, q5a, q11b and q23. Further, let us assume that in each of these product variables, a 5 equates to your client’s brand and a NaN indicates the customer does not have the product. We can compute the share of wallet in this instance as follows:

var a = new Array;
if (!isNaN(q1c)) a.push(q1c == 5);
if (!isNaN(q5a)) a.push(q5a == 5);
if (!isNaN(q11b)) a.push(q11b == 5);
if (!isNaN(q23)) a.push(q23 == 5);
if (a.length == 0) {
  NaN;
} else {
  var result = 0;
  for (var i = 0; i < a.length; i ++)
    result += a[i];
  result / a.length;
}

Key features to note about this example are:

  • var a = new Array creates a new array which initially contains nothing (an array is a list of objects, such as numbers).
  • !isNaN returns a true if a it is not a missing value (i.e., ! indicates not).
  • a.push appends something to the array called a, increasing its size.
  • q1c == 5 returns a value of true if q1c is equal to 5 and false otherwise; this is equivalent to returning a value of 1 or 0.
  • a.length returns the number of entries in the array called a. Note that in this example this number will differ depending upon the number of products that the user has.
  • A new variable, result, is initialized with a value of 0.
  • A for loop is used to loop through all the contents of the array, first making i take a value of 0, then 1, etc.
  • a[i] returns the first entry of the array when i is 0, the second when i is 1, etc.
  • += indicates that the value if a[i] is added to result. It is equivalent to writing result = result + a[i].
  • If we wanted to reuse this code at a later stage, we could do so by modifying only the lines of code beginning with if (!isNaN).

See also

For an automated solution to the same problem, see Create New Variables - Case-Level Shares.