Ad

Selecting Values From An Arry And Storing In A Variable

- 1 answer

I am trying to return the second and third value in an array - but struggling to do so with my limited JS knowledge.

I have two arrays which are combined into one and looks like this:

"0.003839795 - clothes ,0.171756425 - food",0.00741361072561247 - electronics"

I want to order the array by highest score, and then pull back the score and the category into separate variables.

category1 = value
category1score = value
cat2 score = value
cat2 score = value

The script below works and can return the top product name, but I can't work out how to make it return the associated score or the second and third prod/scores in the array...

var product;
var finalString=","+user.get('array1')+user.get('array2');
var finalArray = finalString.split(',');
product = finalArray.sort()[finalArray.length - 1] +' - ';
return product.split(' - ')[1];

The output for above array would look like:

cat1 = food 
cat1score = 0.171756425 
cat2 = electronics 
cat2score = 0.00741361072561247 
cat3= clothes 
cat3score = 0.003839795 
Ad

Answer

Here is an approach that uses a temporary array of objects, and sorts by a field in the object. The parsing provides some flexibility for optional spaces. It also converts the score to a float to ensure leading zeros, negative signs, etc, do not cause inaccurate ordering.

const data = `0.003839795 - clothes ,0.171756425 - food ,0.00741361072561247 - electronics`

let items = [];

const parts = data.split(/\s*,\s*/)
parts.forEach(function (part) {
  const pair = part.split(/\s*-\s*/);
  items.push({
    score: parseFloat(pair[0]),
    name: pair[1]
  });
})

// sort by score, descending
items.sort(function (a, b) { return b.score - a.score });

for (let i = 0; i < items.length; i++) {
  console.log('cat' + (i+1) + '= ' + items[i].name);
  console.log('cat' + (i+1) + 'score= '+ items[i].score);
}

Here is your updated snippet. You need to sort and then reverse. And change the order of some of your logic.

var product;
var finalString = `,,,0.003839795 - clothes ,0.171756425 - food ,0.00741361072561247 - electronics`

var finalArray = finalString.split(',');
finalArray.sort().reverse()
finalArray = finalArray.filter(function(it) {
  return it.trim().length > 0
})

var rets=[];
for (var i = 0; i < finalArray.length; i++) {
  var product = finalArray[i]
  var pair = product.split(' - ');

  var ret = {
    product: pair[1],
    score: pair[0]
  }
  rets.push(ret)
  console.log(ret)
}

Ad
source: stackoverflow.com
Ad