skip to Main Content

So I am very new to coding and have run into an issue when it comes to comparing arrays, especially ones that are nested and trying to pull out values that match using their indices into a new array. Say I have two different arrays in the example where one is a nested array:


const array1 = [1,2,3,4,5,6,7,8,9,10]

const array2 = 
[
[1,2,4,6]
[1,3,7,9,10]
[1,2]
[1,6,8,9]
]

I need the nested array to check each value against the original array to see if it matches and if it does then pull that value into a new array at the same index. IF it doesn’t match at that index then I need it to inert a delimiter or blank value of some kind then finish comparing the rest of the values against the two arrays. I also need the new outputted array to be the same length of the original array, so the expected output for the values above would be:

const ouputtedArray = 
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]
I have tried a couple of different approaches and spent hours online looking for the answer with no hope. For example I have tried to compare the two arrays using a for loop:
for(let i = 0; i <=array1.length;i++){
            if( i + array2[0][i] ==  i + array1[i]){
                const match = i + array2[0][i]
                const arrays =[]
                console.log([match])
            }}

//console.log output
['1']
['2']

The end goal of this entire process is to be able to input this data into a spreadsheet, so I need to keep the blanks to represent empty cells within CSV format, so eventually the overall data would be:

const array1 = [1,2,3,4,5,6,7,8,9,10] // These are the headers for the spreadsheet

const ouputtedArray = // these are the data cells
[
[1,2,,4,,6,,,,,]
[1,,3,,,,7,,9,10]
[1,2,,,,,,,,,]
[1,,,,,6,,8,9,]
]  

and the spreadsheet itself would look like this


| 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 | 10 | 
| - | - | - | - | - | - | - | - | - | -- |
| 1 | 2 |   | 4 |   | 6 |   |   |   |    |
| 1 |   | 3 |   |   |   | 7 |   | 9 | 10 |
| 1 | 2 |   |   |   |   |   |   |   |    |
| 1 |   |   |   |   | 6 |   | 8 | 9 |    |

I have no idea what to do here and am struggling to find a solution. Any help would be absolutely amazing!

3

Answers


  1. Assuming

    • The lists are always sorted.
    • There are no duplicate items in the list
    • Every item in each sublist in array2 belongs to items in array1

    You should be able to use the following:

    function alignArrays(arr1, arr2) {
        const result = new Array(arr1.length).fill('');
        let j = 0;
    
        for (let i = 0; i < arr1.length; i++) {
            while (j < arr2.length && arr2[j] < arr1[i]) {
                j++;
            }
            if (j < arr2.length && arr1[i] === arr2[j]) {
                result[i] = arr2[j];
                j++;
            }
        }
    
        return result;
    }
    
    const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const array2 =
        [
            [1,2,4,6],
            [1,3,7,9,10],
            [1,2],
            [1,6,8,9]
        ]
    
    const alignedArray = [];
    array2.forEach((arr) => alignedArray.push(alignArrays(array1, arr)))
    console.log(alignedArray);
    Login or Signup to reply.
  2. It sounds like you’re trying to compare the values in a nested array against a main array and insert matching values into new arrays, while leaving blanks for missing values. This can be done by iterating over the array2 nested arrays and comparing them against array1, inserting values into a new array when there’s a match and inserting a blank or delimiter when there isn’t.

    Here’s a step-by-step approach and the code to achieve this:

    Steps:

    1. Loop through each sub-array in array2.
    2. For each sub-array, compare its values with array1.
    3. If a value from the sub-array matches a value in array1 (at any
      index), insert that value at the correct index in the new array.
    4. If there’s no match at an index, insert an empty value (e.g., null
      or ”).
    const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    
    const array2 = [
      [1, 2, 4, 6],
      [1, 3, 7, 9, 10],
      [1, 2],
      [1, 6, 8, 9]
    ];
    
    const outputArray = array2.map(subArray => {
      const result = new Array(array1.length).fill(null); // Initialize a new array with `null` or empty values
      subArray.forEach(value => {
        const index = array1.indexOf(value); // Find the index of the value in array1
        if (index !== -1) {
          result[index] = value; // If found, insert it at the correct index
        }
      });
      return result;
    });
    
    console.log(outputArray);

    Once you have this array, converting it to a CSV format for your spreadsheet can be done easily by joining each sub-array into a comma-separated string:

    const arrayToCSV = outputArray.map(row => row.map(item => item === null ? '' : item).join(',')).join('n');
    console.log(arrayToCSV);

    OUTPUT

    1,2,,4,,6,,,,
    1,,3,,,7,,9,10
    1,2,,,,,,,,
    1,,,,,6,,8,9,
    

    This will provide the output you need in CSV format, with empty values where there are no matches, making it ready to insert into a spreadsheet.

    Customization:

    1. You can replace null with ” or any other delimiter you need.
    2. The code uses array1.indexOf() to locate the value’s index in the
      main array. This method works as long as the values are primitives
      (like numbers or strings). If you’re dealing with objects, you’d
      need a custom comparison function.
    Login or Signup to reply.
  3. Decomposing a little, we want a clone of array1 substituting missing values with something like empty string, then we want to apply that to every subarray in array2

    const array1Cloner = ar => array1.map(el => ar.includes(el) ? el : '');
    const result = array2.map(array1Cloner);
    

    That’s it.

    const array1 = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
    const array2 = [[1, 2, 4, 6], [1, 3, 7, 9, 10], [1, 2], [1, 6, 8, 9]];
    
    const delimeter = '';  // set this to whatever you want to substitute for missing elements
    
    const array1Cloner = ar => array1.map(el => ar.includes(el) ? el : delimeter);
    const result = array2.map(array1Cloner);
    console.log(result);
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search