Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

concatenate after in JAVASCRIPT

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).

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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"]

>Solution :

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 into 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);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading