Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split array (uneven chunks) when item value ends with " ago"

I need to split array that chunks are uneven unfortunately, however I know that every new array ends with item that has ago(space ago) in the value.

const arrExample = ["Blah","559","86,758","4.05","2.38","-4.48%","-0.44%","13,562","30d ago", "Trall","531","210,676","16","15","-3.8%","4,955","403d ago", "Shibu","506","991,748","84","6.71%","5,897","667d ago", "Mommy","404","35,083","1.64","1.64","-8.38%","17%","7,378","323d ago","Rocket","403","274",".4088",".355","-","-","483","47h ago"...]

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Just iterate through your input array, test for your substring, and push array slices into your output array.

const input = ["Blah","559","86,758","4.05","2.38","-4.48%","-0.44%","13,562","30d ago", "Trall","531","210,676","16","15","-3.8%","4,955","403d ago", "Shibu","506","991,748","84","6.71%","5,897","667d ago", "Mommy","404","35,083","1.64","1.64","-8.38%","17%","7,378","323d ago","Rocket","403","274",".4088",".355","-","-","483","47h ago"];
const output = [];
const n = input.length; // cache length
for (let i = 0, x = 0; i < n; i++) {
  if (input[i].endsWith(" ago")) {
    output.push(input.slice(x, i + 1)); // push the entire chunk
    x = i + 1;
  }
}
console.log(output);

Note: slicing and pushing the entire chunk should be more efficient than pushing individual values… with the efficiency scaling with your input/chunk size.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading