jquerysplit

split and separate based on specific values - jQuery


Basically my string looks like this:

568|896|2015-12-14 13:43:05||1|6666698|text1|999969|624|0|1|0|1^696|982|2015-11-14 13:43:05||2|6666695|text2|899969|634|0|0|0|0^147|111|2015-10-14 13:43:05||3|6666694|text3|799969|644|0|0|0|0^025|558|2014-09-14 13:43:05||4|6666693|text4|699969|654|0|1|0|1^925|777|2014-08-14 13:43:05||5|6666692|text5|599969|664|0|1|0|1^

Then I am splitting this string by ^ character

var allvalues = $('#allvalues').val();
var spval = allvalues.split('^');

console.log(spval[0])+"<br>";
console.log(spval[1])+"<br>";
console.log(spval[2])+"<br>";
console.log(spval[3])+"<br>";
console.log(spval[4])+"<br>";

Now this will give:

568|896|2015-12-14 13:43:05||1|6666698|text1|999969|624|0|1|0|1
696|982|2015-11-14 13:43:05||2|6666695|text2|899969|634|0|0|0|0
147|111|2015-10-14 13:43:05||3|6666694|text3|799969|644|0|0|0|0
025|558|2014-09-14 13:43:05||4|6666693|text4|699969|654|0|1|0|1
925|777|2014-08-14 13:43:05||5|6666692|text5|599969|664|0|1|0|1

Now here I want to check each array after the split. And I want to separate the array based on last 4 numbers, in which all 4 numbers should be 0 [0|0|0|0], within the array which are separated by | pipe characters.

After the separation, I should get

696|982|2015-11-14 13:43:05||2|6666695|text2|899969|634|0|0|0|0
147|111|2015-10-14 13:43:05||3|6666694|text3|799969|644|0|0|0|0

AND

568|896|2015-12-14 13:43:05||1|6666698|text1|999969|624|0|1|0|1
025|558|2014-09-14 13:43:05||4|6666693|text4|699969|654|0|1|0|1
925|777|2014-08-14 13:43:05||5|6666692|text5|599969|664|0|1|0|1

How do I achieve this?


Solution

  • You can iterate and put the values in two seperate arrays

    var allvalues = $('#allvalues').val();
    var spval     = allvalues.split('^');
    var arr2      = [];
    var arr1      = spval.filter(function(item) {
        if (item.trim().length === 0) return false;
        if (item.split('|').join('').slice(-4) === "0000") {
            arr2.push(item);
            return false
        }
        return true;
    });
    

    FIDDLE