Home > database >  Bash array transformation like .map() in JavaScript
Bash array transformation like .map() in JavaScript

Time:01-24

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[*]}

CodePudding user response:

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.

CodePudding user response:

It is possible to implement an array_walk with a callback to perform operation on each element this way:

#!/usr/bin/env bash

# Applies the user-defined callback function to each element of the array. 
#
# @params
# $1: The array name to walk
# $2: The callback command or function name
array_walk() {
  local -n __array=$1
  local -- __callback=$2 __i
  for __i in "${!__array[@]}"; do
    "$__callback" "$1[$__i]"
  done
}

x2() {
  local -n __e=$1
  __e=$((2 * __e))
}

array1=(1 4 9 16)

array_walk array1 x2

printf '%s\n' "${array1[*]}"
  •  Tags:  
  • Related