Search code examples
javascriptarraysobjectbindingbind

Updating an array of objects with another array of different length


I have an array of objects with a single key value pair, and an array of strings that could be smaller in length than the object array.

let objectArray = [
    {foo: ''},
    {foo: ''},
    {foo: ''},
    {foo: ''},
    {foo: ''}
  ]

let stringArray = ['a','b','c']

I want to assign the string array, in order, to the foo key in the object array. And the string array will be reused if it is shorter in length. For example, the wanted output is:

let result = [
    {foo: 'a'},
    {foo: 'b'},
    {foo: 'c'},
    {foo: 'a'},
    {foo: 'b'}
  ]

What is the most efficient way to achieve this outcome?


Solution

  • You're probably going to want to use the remainder (%) operator to "wrap around".

    See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Remainder


    let objectArray = [
      {foo: ''},
      {foo: ''},
      {foo: ''},
      {foo: ''},
      {foo: ''}
    ];
    let stringArray = ['a','b','c'];
    
    console.log(
      objectArray.map((elem, idx) => {
        elem.foo = stringArray[idx % stringArray.length];
        return elem;
      })
    );