-1

I have two arrays, initialArray and testArray. initialArray consists of 8 arrays each with a single element(an object), testArray consists of 8 elements (each an object). I want to pop and push each of the elements in testArray to an array in initialArray when a condition is met so I end up with an empty testArray and initialArray[0]..[7] will each have one of the testArray elements.

var initialArray = [
    [{optiona:'some string',optionb: 'some string'}],
    [/*...*/],
];
var testArray = [
    {optiona:'some other string',optionb: 'some other string'},
    {/*...*/}
];

The final initialArray should look like

[
    [
        {optiona:'some string',optionb: 'some string'},
        {optiona:'some other string',optionb: 'some other string'}
    ],
    [
        {..},
        {..}
    ],
    // ,,,
]

My code so far:

var mySomeFunction = function(element, index, array) {
    // test if elements are not equal to (element.optiona != option1 && element.optionb != option2);
    //return the element
}

initialArray.forEach(function(item) { 
    //get the conditionals for the current element
    var option1 = item[0].optiona
    var option2 = item[0].optionb

    item.some(mySomeFunction)
    // item.push(element returned from mySomeFunction)
});  

I'm not sure how to use the .some method properly, I need to pass the values option1 and option2 that relate to the current element e.g initialArray[0][0], choose an element that values don't match the values of option1 and option2, e.g testArray[3], pop the element and push it onto the current array in initialArray, e.g initialArray[0][0] now contains the element testArray[3].

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
raphael_turtle
  • 7,154
  • 10
  • 55
  • 89

1 Answers1

1

I don't think some will be of much help here. It will either return true or false, so it does not tell you which element meets the condition.

You could use a normal loop:

initialArray.forEach(function(item) { 
    //get the conditionals for the current element
    var option1 = item[0].optiona
    var option2 = item[0].optionb

    for(var i = 0, len = testArray; i < len; i++) {
        if(testArray[i].optiona !== option1 && testArray[i].optionb !== option2) {
            item.push(testArray[i]);
            testArray.splice(i, 1); // remove element from array
            break;
        }
    }
}); 

Note that forEach is part of ECMAScript 5 and not available in older browsers.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143