How to resolve the algorithm Hash from two arrays step by step in the jq programming language

Published on 12 May 2024 09:40 PM
#Jq

How to resolve the algorithm Hash from two arrays step by step in the jq programming language

Table of Contents

Problem Statement

Using two Arrays of equal length, create a Hash object where the elements from one array (the keys) are linked to the elements of the other (the values)

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Hash from two arrays step by step in the jq programming language

Source code in the jq programming language

# hash(keys) creates a JSON object with the given keys as keys
# and values taken from the input array in turn.
# "keys" must be an array of strings.
# The input array may be of any length and have values of any type,
# but only the first (keys|length) values will be used; 
# the input will in effect be padded with nulls if required.
def hash(keys):
  . as $values
  | reduce range(0; keys|length) as $i
      ( {}; . + { (keys[$i]) : $values[$i] });

[1,2,3] | hash( ["a","b","c"] )

jq -n -f Hash_from_two_arrays.jq
{
  "a": 1,
  "b": 2,
  "c": 3
}

{
  "1": 10,
  "2": 20,
  "3": 30
}

  

You may also check:How to resolve the algorithm Case-sensitivity of identifiers step by step in the OCaml programming language
You may also check:How to resolve the algorithm Number names step by step in the XPL0 programming language
You may also check:How to resolve the algorithm Order two numerical lists step by step in the Picat programming language
You may also check:How to resolve the algorithm Metered concurrency step by step in the BBC BASIC programming language
You may also check:How to resolve the algorithm Check that file exists step by step in the Phix programming language