Arpit Kumar
Arpit Kumar

Reputation: 2249

create a string based on different parameters javascript

I want to generate a string based on user input, it should looks like: 1234-2016-abc12-3232, i have 7 options like roll_number, user_id, user_name, year, department, class, subject_code. The sequence of this options is user define. Ex: a user can say i want user_name first then subject_code then roll_number and so on, user can also choose how many character he wants from a particular option means he can say last 2 character from roll_number, first 3 character from user_name and so on.

===What i tried===

First i captured all the information in 4 array:

The first array is:

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];

so i got the list of options which i have to take for string creation.

The second array is:

var sequence = [
                    { key:'user_name', value:2 },
                    { key:'subject_code', value:3 },
                    { key:'class', value:1 },
                    { key:'roll_number', value:4 },
                ];

this array gives the sequence of option.

Third array is:

var alignment = [
            { key:'user_name', value:'left' },
            { key:'subject_code', value:'left' },
            { key:'class', value:'right' },
            { key:'roll_number', value:'left' },
        ];

It gives the knowledge of alignment for example if roll_number is 123456 and user selected the length as 3 from right then 456 should be taken, so this is the left and right information.

The fourth array is:

var lengthOfOptions = [
            { key:'user_name', value:3 },
            { key:'subject_code', value:4 },
            { key:'class', value:2 },
            { key:'roll_number', value:5 },
        ];

===Then===

The values of this options:

        var user_name = "1234abcd";
        var subject_code = "567890";
        var class = "2016";
        var roll_number = "123";

Now using for loop i got the name of options, then i tried to get the sequence but i am not able to get the sequence of a particular option because i am inside for loop and i am not sure i should get sequence first or option name first if you have any simple approach or a guideline for me please help, my point of view is i need to run loop inside loop but i don't know how? Thanks.

==EDIT==

my code for loop is

            sequence.sort(function(a, b) {
                return parseFloat(a.value) - parseFloat(b.value);
            });
            for (var i = 0; i <= sequence.length - 1; i++){
                console.log("The key is :", sequence[i]['key']);
                console.log("The value is :", sequence[i]['value']);
            }

after this what to do i am not able to understand.

Upvotes: 1

Views: 89

Answers (2)

kukkuz
kukkuz

Reputation: 42352

First you can sort the sequence and then use Array.prototype.reduce to calculate the length and alignment of each of the selectedOptions and concat it to the required string:

Demo below:

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];
var sequence = [{ key:'user_name', value:2 },{ key:'subject_code', value:3 },{ key:'class', value:1 },{ key:'roll_number', value:4 },];
var alignment = [{ key:'user_name', value:'left' },{ key:'subject_code', value:'left' },{ key:'class', value:'right' },{ key:'roll_number', value:'left' },];
var lengthOfOptions = [{ key:'user_name', value:3 },{ key:'subject_code', value:4 },{ key:'class', value:2 },{ key:'roll_number', value:5 },];

// input values
var options={user_name:"1234abcd",subject_code:"567890", class:"2016",roll_number:"123"};

var result = sequence.sort(function(a, b) {
  return a.value - b.value;
}).reduce(function(prev, curr) {
  // if sequence elements are selected options
  if (selectedOptions.indexOf(curr.key) !== -1) {
    // find length and alignment
    var length = Math.min(lengthOfOptions.filter(e => e.key == curr.key)[0].value, options[curr.key].length);
    var align = alignment.filter(e => e.key == curr.key)[0].value;

    // extract the substring from input
    if (align == "left") {
      prev.push(options[curr.key].slice(0, length));
    } else {
      prev.push(options[curr.key].slice(-length));
    }
    return prev;
  }
}, []).join('-');

console.log(result);

Note the Math.min used while calculating the length - to check if the lengthOption exceeds the input value size.

EDIT:

So if you want to put a padding of 0 in case the lengthOption is more than the input value, you can use this. Cheers!

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];
var sequence = [{ key:'user_name', value:2 },{ key:'subject_code', value:3 },{ key:'class', value:1 },{ key:'roll_number', value:4 },];
var alignment = [{ key:'user_name', value:'left' },{ key:'subject_code', value:'left' },{ key:'class', value:'right' },{ key:'roll_number', value:'left' },];
var lengthOfOptions = [{ key:'user_name', value:3 },{ key:'subject_code', value:4 },{ key:'class', value:2 },{ key:'roll_number', value:5 },];

var options={user_name:"1234abcd",subject_code:"567890", class:"2016",roll_number:"123"};

var result = sequence.sort(function(a, b) {
  return a.value - b.value;
}).reduce(function(prev, curr) {
  if (selectedOptions.indexOf(curr.key) !== -1) {
    var lengthOption = lengthOfOptions.find(e => e.key == curr.key).value;
    var align = alignment.find(e => e.key == curr.key).value;
    var padding = Math.max(lengthOption - options[curr.key].length, 0);
    if (align == "left") {
      prev.push(Array(padding + 1).join(0) + options[curr.key].slice(0, Math.min(lengthOption, options[curr.key].length)));
    } else {
      prev.push(Array(padding + 1).join(0) + options[curr.key].slice(-Math.min(lengthOption, options[curr.key].length)));
    }
    return prev;
  }
}, []).join('-');

console.log(result);

Upvotes: 1

Weedoze
Weedoze

Reputation: 13943

In your case, the roll_number will be empty thus you will see a hyphen at the end of the final string

var selectedOptions = ['user_name', 'roll_number', 'subject_code', 'class'];
var sequence = [{
  key: 'user_name',
  value: 2
}, {
  key: 'subject_code',
  value: 3
}, {
  key: 'class',
  value: 1
}, {
  key: 'roll_number',
  value: 4
}, ];

var alignment = [{
  key: 'user_name',
  value: 'left'
}, {
  key: 'subject_code',
  value: 'left'
}, {
  key: 'class',
  value: 'right'
}, {
  key: 'roll_number',
  value: 'left'
}, ];

var lengthOfOptions = [{
  key: 'user_name',
  value: 3
}, {
  key: 'subject_code',
  value: 4
}, {
  key: 'class',
  value: 2
}, {
  key: 'roll_number',
  value: 5
}, ];

var object = {
  "user_name": "1234abcd",
  "subject_code": "567890",
  "class": "2016",
  "roll_number": "123"
}

var result = [];

//Iterate each option
for (var i = 0; i < selectedOptions.length; i++) {
  var key = selectedOptions[i];
  var seq = sequence.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the sequence number
  var align = alignment.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the alignement value
  var length = lengthOfOptions.filter(function(v, i) {
    return v.key === key;
  })[0].value; //Get the length value

  var string = object[key]; //Get the string to modify
  if (align === "left") {
    string = string.slice(length);
  } else {
    string = string.slice(0, string.length - length);
  }

  result[seq - 1] = string; //Add the string in an array at the correct sequence index.
}

var finalString = result.join("-"); //Concat all the strings with '-'

console.log(finalString);

Upvotes: 1

Related Questions