Concatenate arrays from the same array in JavaScript

javascript merge two arrays without duplicates
javascript merge array of objects by key
javascript append array to array
concat multiple arrays javascript
merge two arrays with same keys javascript
javascript array push
merge two arrays java
combine two arrays python

I have an array like this:

[
  {
    "id": 10002,
    "flag": false,
    "list": [
      "aaa",
      "bbb"
    ]
  },
  {
    "id": 10001,
    "flag": true,
    "list": [
      "10002",
      "10003"
    ]
  },
  {
    "id": 10003,
    "flag": false,
    "list": [
      "ccc",
      "ddd"
    ]
  }
]

i tried this initially i have "10001" value so iterate this array to take "list" array if flag==true then stored into newarray. but its not working.

I want it to be like this: [ "aaa", "bbb", "ccc", "ddd" ].

const array = [
  {
    id: 10001,
    flag: true,
    list: ["10002", "10003"]
  },
  {
    flag: false,
    id: 10002,
    list: ["aaa", "bbb"]
  },
  {
    flag: false,
    id: 10003,
    list: ["ccc", "ddd"]
  }
];

const isHead = item => item.flag && item.id === 10001;

const head = array.find(isHead);

const rest = array.filter(item => !isHead(item));

const result = rest
  .flatMap(item =>
    head.list.includes(item.id.toString()) && item.list
  );

console.log(result);

Array.prototype.concat(), Learn how to merge two arrays together in JavaScript. arrays using the addition operator, but JavaScript Array objects actually have a method called concat You can also accomplish the same thing using spread syntax. We've seen different approaches to concatenate multiple arrays into a single one: Using the Array.prototype.push () method Using the Array.prototype.concat () method Using spread syntax in array literals

If i understand correctly this is what you want:

const someArray = [
  {
    "id": 10001,
    "list": [
      "10002",
      "10003"
    ]
  },
  {
    "id": 10002,
    "list": [
      "aaa",
      "bbb"
    ]
  },
  {
    "id": 10003,
    "list": [
      "ccc",
      "ddd"
    ]
  }
];

const [head,...rest] = someArray;
const result = head.list.reduce((acc,currentId)=>acc.concat(rest.find(({id})=> id === parseInt(currentId)).list),[]);

Here is a jsFiddle https://jsfiddle.net/sudakatux/9hju85mt/22/

Explanation: take the head and splitted from the rest since the head contains the ids. using the head as a dictionary find each list for each id in the head and concatenate

note the id must be in the subsequent list else it will fail with undefined. if you want to account for this error you can set a defualt empty object with a list. for example this part:

rest.find(({id})=> id === parseInt(currentId)).list

Will look like

rest.find(({id})=> id === parseInt(currentId)) || {list:[]}).list

Which basically means if its undefined return an object that has an empty list so then it will concatenate an empty list which results in being the same list. (like multiplying by 1 in a multiplication)

Hope it helps.

EDIT after your edit.

If your array is in different order you need to find the dictonary and then the logic is the same

  const [newHead] = otherArray.filter(({list}) => list.every(elem=>!isNaN(elem)));

    const result2 = newHead.list.reduce(
    (acc,currentId) =>acc.concat(otherArray.find(({id})=> id === parseInt(currentId)).list),[]);

if you are testing for the flag then your head filter would look like. the blocks are the same the only thing that changes is the condition.

const [newHead] = otherArray.filter(({flag}) => flag));

(note* that instead of using the rest i used the complete array(otherArray). since im targeting equality. Im using filter and extracting the first element of the result. because im accounting for the possibility that in the future you may have more than one "dictionary element". if thats the case in the future then you just have to concat the lists from the filter result

2 Ways to Merge Arrays in JavaScript, Now the second method is like a shortcut; you just have to store the values of two or more arrays in a different array using ellipses or spread  The concat () method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array. JavaScript Demo: Array.concat ()

You can map over the list of the first item and concat all the lists from those ids.

const mapItems = (input) => {
  const source = input[0].list;
  source.reduce((results, id) => {
    return results.concat(input.find(item => item.id === id).list);
  }, []);
};

mapItems([
  {
    "id": 10001,
    "list": [
      "10002",
      "10003"
    ]
  },
  {
    "id": 10002,
    "list": [
      "aaa",
      "bbb"
    ]
  },
  {
    "id": 10003,
    "list": [
      "ccc",
      "ddd"
    ]
  }
]);

How to merge two arrays in JavaScript and de-duplicate items , This often comes up when manipulating listed data with the use Arrays. JavaScript exposes an array-like object arguments which contains the values of all the ES6 however offers us a cleaner and more concise way to achieve the same  @ignis This is not a duplicate. That question is specifically asking about removing duplicates in the resulting array. It is more specific, and this question is much more general.

You can fetch the values of the list of first object in the array as arr[0]['list'] Once you have these values (10002,10003) then you can fetch the list values of remaining objects in the array whose id key matches one of the above values.

if(arr[i]['id'] == 10002 || arr[i]['id'] == 10003){
//fetch the list values
}

How to Merge Two Arrays in JavaScript, JavaScript exercises, practice and solution: Write a JavaScript function to merge two arrays and removes all duplicates elements. # 2 Ways to Merge Arrays in JavaScript. Here are 2 ways to combine your arrays and return a NEW array. I like using the Spread operator. But if you need older browser support, you should use Concat.

Three Ways to Combine Arrays in JavaScript, Merging two arrays, whether the arrays already exist or the second array is yet to be defined, is a common task. Moreover, if you're not careful  Concatenating arrays in JavaScript can be done with the concat () method. The concat () method is used to merge two or more arrays. This method does not change the existing arrays, but instead returns a new array.

Combining Arrays Without Duplicates ― Scotch.io, concat() method is used to merge two or more arrays together. This method does not alter the original arrays passed as arguments. Syntax: var new_array =  Concatenate typed arrays Given an array of Uint8Array, write a function concat (arrays) that returns a concatenation of them into a single array. Open a sandbox with tests.

JavaScript array: Merge two arrays and removes all duplicates , Array#concat(..) is the tried and true approach for combining two (or more!) arrays. But the hidden danger is that it's creating a new array instead of modifying one of the existing ones. But the hidden danger is that it's creating a new array instead of modifying one of the existing ones.

Comments
  • use array.splice
  • And what did you try to achieve the desired output?
  • i dont follow. you want to concatinate the lists for the same id?
  • yes it is working.. but sometimes data like this [ { "id": 10002, "flag": false, "list": [ "aaa", "bbb" ] }, { "id": 10001, "flag": true, "list": [ "10002", "10003" ] }, { "id": 10003, "flag": false, "list": [ "ccc", "ddd" ] } ]
  • If I understood your correctly, first item must be flagged, other shouldn't be?
  • we cant take first as head.. may be position changed. so which object has id == 10001 and flag === true only as head array
  • I updated my solution, check it please
  • we cant take first as head.. may be position changed. so which object has id == 10001 and flag === true only as head array
  • updated both fiddle and explanation