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

Bash array transformation like .map() in JavaScript

In JavaScript, the Array.map() function exists such that

const array1 = [1, 4, 9, 16];
const map1 = array1.map(x => x * 2);
console.log(map1);
// expected output: Array [2, 8, 18, 32]

I need a bash equivalent where I can take my array, manipulate its contents, then receive a new array with the manipulations.

array1=(1 4 9 16)
map1=# ????
echo ${map1[*]}

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

>Solution :

Soooooooo, just write the loop.

array1=(1 4 9 16)
map1=()
for i in "${array1[@]}"; do
   map1+=("$((i * 2))")
done
echo "${map1[@]}"

Might be a good time to re-read an introduction to Bash arrays.

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