Home > other >  concatenate after in JAVASCRIPT
concatenate after in JAVASCRIPT

Time:06-08

I have an array of strings.

For e.g. column_list=["ab","bc","cd","asv_a","asv_f","asv_l","asv_x", "xy","yz"].

Now I have another array with only the"asv_" value(which can be repeated or unique).

For e.g. new_column = ["asv_b", "asv_f", "asv_s"].

Now I want to create a new array by concatenating the new_column array to column_list such that all the asv_ values be together in the middle and unique.

Expected outcome -

result = ["ab","bc","cd","asv_a","asv_f","asv_l","asv_x","asv_b", "asv_s", "xy","yz"]

CodePudding user response:

First, create a Set of asv_* values in column_list for use in eliminating duplicates

const asvValues = new Set(column_list.filter(v => v.startsWith("asv_")));

Then filter out duplicates

const inserts = new_column.filter(v => !asvValues.has(v));

Now, find the index of the last asv_ entry

const lastAsv = column_list.lastIndexOf([...asvValues].pop());

Now use splice() to insert the filtered array after the position found

column_list.splice(lastAsv   1, 0, ...inserts);

const column_list=["ab","bc","cd","asv_a","asv_f","asv_l","asv_x", "xy","yz"];
const new_column = ["asv_b", "asv_f", "asv_s"];

const asvValues = new Set(column_list.filter((v) => v.startsWith("asv_")));
const inserts = new_column.filter((v) => !asvValues.has(v));
const lastAsv = column_list.lastIndexOf([...asvValues].pop());
column_list.splice(lastAsv   1, 0, ...inserts);

console.log(column_list);

CodePudding user response:

You can use method mergedArr to create an array with Array.prototype.reduce() to keep the order and then with Object.values() and Array.prototype.flat() to build the result as a Set of unique values

Code:

const column_list = ["ab","bc","cd","asv_a","asv_f","asv_l","asv_x", "xy","yz"]
const new_column = ["asv_b", "asv_f", "asv_s"]
const mergedArr = (arr, newArr) => Object
  .values(
    arr.reduce((a, c, i) => {
      const isStartsWithAsv = c.startsWith('asv_')
      const index = isStartsWithAsv
        ? 1
        : !isStartsWithAsv && !a[1].length 
          ? 0 
          : 3
      a[index].push(c)
      return a
    }, [[], [], newArr, []])
  )
  .flat()
  
const result = [...new Set(mergedArr(column_list, new_column))]

console.log(result)

  • Related