0

I have a list of numbers that is a string value using a loop I want to split this string into different variables in an array, the first of length 3 and the 6 of length 7 and the last of length 3. How can this be done using functions and loops.

this is the simple way I've done it, however I want to achieve the same outcome but using loops

1
  • is the length of strinngg is fixed ? Commented Aug 18, 2018 at 15:53

4 Answers 4

1

We could do something like this:

 
let str = '000111111122222223333333444444455555556666666mmmm';

// Defines the lengths we're using
let lengths = [3,7,7,7,7,7,7,3];

let index = 0;

let result = lengths.reduce((acc,n) => {
    acc.push(str.slice(index, index += n));
    return acc;
} , [])

console.log(result);

Sign up to request clarification or add additional context in comments.

Comments

1

You could map the sub strings.

var str = '000111111122222223333333444444455555556666666mmmm',
    lengths = [3, 7, 7, 7, 7, 7, 7, 3],
    result = lengths.map((i => l => str.slice(i, i += l))(0));

console.log(result);

2 Comments

what does the l mean in this code, when you say i => l i don't understand how this works as you have not defined l. Thanks in advance
(i => l => str.slice(i, i += l))(0) is an IIFE with a closure over i with value 0 and it returns a function as callback of l => str.slice(i, i += l), where the l takes a single length and adds it to i for the substring.
0

Here's one way to do that:

let theArray = document.getElementById('theArray');
let theVariable = document.getElementById('theVariable');
let targetString = "122333444455555666666";
let dataSizes = [1, 2, 3, 4, 5, 6];
var result = [];
var pos = 0;
dataSizes.forEach( (size) => {
    result.push(targetString.substr(pos, size));
    pos += size;
});
theArray.textContent = result.toString();
let [one, two, three, four, five, six] = result;
theVariables.textContent = `${one}-${two}-${three}-${four}-${five}-${six}`;

Comments

0

a generic way of doing this will be, if you want in a variable you can use subStringLengthMaps key, :-

let str="abcdefghijklmnopqrstu";
let  subStringLengthMap={a:3, b:7, c:7 , d:3};

//making pure funciton
var getStrings = function(str, subStringLengthMap){
  let result =[];
  Object.keys(subStringLengthMap).forEach(function(key){
  let temp = str.slice(0, subStringLengthMap[key]);
  result.push(temp);
    str = str.replace(temp,'');
  })

  return result;

}

//call the function
console.log(getStrings(str, subStringLengthMap))

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.