skip to Main Content

I have a strange situation for filtering duplicates.

I have to turn this

[
  {name: A, number: 1, order: 1},
  {name: B, number: 1, order: 2},
  {name: C, number: 1, order: 3},
  {name: D, number: 2, order: 4},
  {name: E, number: 2, order: 5},
  {name: F, number: 1, order: 6}
]

Into

[
  [
    {name: A, number: 1, order: 1},
    {name: B, number: 1, order: 2},
    {name: C, number: 1, order: 3},
  ],
  [
    {name: D, number: 2, order: 4},
    {name: E, number: 2, order: 5},
  ],
  [
    {name: F, number: 1, order: 6}
  ]
]

I have been able to put duplicates into their own arrays but this extra step has me scratching my head.

2

Answers


  1. Here’s an example function that organizes the array based on the "number" property:

    function arrangeArrayByNumber(arr) {
      const result = [];
      let currentNumber = null;
      let currentGroup = [];
    
      for (const obj of arr) {
        if (obj.number !== currentNumber) {
          if (currentGroup.length > 0) {
            result.push(currentGroup);
          }
          currentNumber = obj.number;
          currentGroup = [];
        }
        currentGroup.push(obj);
      }
    
      if (currentGroup.length > 0) {
        result.push(currentGroup);
      }
    
      return result;
    }
    

    then you can use it like the following:

    const originalArray = [
      {name: "A", number: 1, order: 1},
      {name: "B", number: 1, order: 2},
      {name: "C", number: 1, order: 3},
      {name: "D", number: 2, order: 4},
      {name: "E", number: 2, order: 5},
      {name: "F", number: 1, order: 6}
    ];
    
    const arrangedArray = arrangeArrayByNumber(originalArray);
    console.log(arrangedArray);
    

    I hope this is what you are looking for 🙂

    Login or Signup to reply.
  2. This approach creates a new subarray each time it notices that the current object’s number property is not the same as the last object’s number property. Otherwise, it adds the current object to the most recent subarray.

    It adds these subarrays to the accumulator of the reduce operation. Note that this approach uses a comma expression to avoid needing braces and the "return" keyword.

    const data = [{"name":"A","number":1,"order":1},{"name":"B","number":1,"order":2},{"name":"C","number":1,"order":3},{"name":"D","number":2,"order":4},{"name":"E","number":2,"order":5},{"name":"F","number":1,"order":6}];
    
    let result = data.reduce((a,c,i,d)=>
      (d[i-1]?.number!==c.number ? a.push([c]) : a[a.length-1].push(c), a), [])
    
    console.log(result)
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search