0

I've got an array that could have 4 digits elements or less (from html select) for example some possible variants of myArray:

myArray = ['1']
myArray = ['4'] 
myArray = ['2', '3']
myArray = ['1', '2', '3', '4'] 
etc...

now I've got an object that has possible variants of myArray for example some possible variants of myObject:

myObject = [
   {active: false, forArrays:['2','4']},
   {active: false, forArrays:['2,3,4','2,4']},
   {active: false, forArrays:['2','1,4']},
   {active: false, forArrays:['2']},
]

I want to change active to true if myArray is exact the same that one of the forArrays variants.

How can I do that? Should I keep forArrays an array as it is or should it be changed to an object to make this problem easier to solve?

gileneusz
  • 1,435
  • 8
  • 30
  • 51

2 Answers2

1

You could iterate the objects and check if forArrays contains comma separated value.

For unsorted values, you could sort them in advanced.

function update(numbers) {
    function asc(a, b) { return a - b; }

    var values = numbers.slice().sort(asc).join();
    myObject.forEach(function (o) {
        if (o.forArrays.some(a => a.split(',').sort(asc).join() === values)) {
            o.active = true;
        }
    });
}

var myObject = [{ active: false, forArrays: ['2', '4'] }, { active: false, forArrays: ['2,3,4', '2,4'] }, { active: false, forArrays: ['2', '1,4'] }];

update(['1']);         // no change
console.log(myObject);

update(['2']);
update(['2', '4']);
console.log(myObject);
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • Thank you for your answer, seems ok, but I cannot assume the same order... That is why I consider to change forArrays values to separate objects/arrays... – gileneusz Mar 02 '18 at 21:31
  • sorry for not responding to your edit, I was quite tired yesterday I and focused on vol7ron answer first. I see your answer is also correct and could be used to solve my problem. Thanks for posting it! – gileneusz Mar 03 '18 at 09:23
1

Given your comments, you can sort and join by commas and compare to each forArray element:

let myArray = ['1','4']

let myObject = [
   {active: false, forArrays:['2','4']},
   {active: false, forArrays:['2,3,4','2,4']},
   {active: false, forArrays:['2','1,4']},
   {active: false, forArrays:['2']},
]

let myArrayString = myArray.sort().join(',');

myObject.forEach( obj => 
  obj.active = obj.forArrays.some( el => 
    myArrayString === el.split(',').sort().join(',') 
  ) 
)

console.log(myObject);
vol7ron
  • 40,809
  • 21
  • 119
  • 172