I have absolutely no clue where to look for.. I have 2 arrays in jQuery and I want to combine the values together. As in: first value array one with first value array 2..
I have 2 arrays, example:
$arrayOne = 'A', 'B', 'C', 'D'
$arrayTwo = '1', '2', '3', '4'
I want to combine these and get the following output
'A': '1',
'B': '2',
'C': '3',
'D': '4',
Any help would be very much appreciated!
Danny
Approach: Loop over the array whose value you want as a key & then push one by one key value pair objects into a map object which is has to declare above the loop.
Note: Both arrays should have the same number of elements.
Code:
$arrayOne = ['A', 'B', 'C', 'D']
$arrayTwo = ['1', '2', '3', '4']
var arrayToMap = new Object(); // or var map = {};
$arrayOne.forEach(function( value, index ) {
arrayToMap[value] = $arrayTwo[index];
});
console.log(arrayToMap);
Output:
{A: "1", B: "2", C: "3", D: "4"}
You can refer the following link if you are new to the array list + loops:
https://api.jquery.com/jquery.each/
Related
I can create a type for an array of N element of string type:
type A = string[];
as well as a predefined number of elements, such as exactly 2 elements:
type A = [string, string];
What I am trying to have is a type that will accept 2 or more elements, but not just one or none.
type A = ?
A = ['a', 'b']; // OK
A = ['a', 'b', 'c']; // OK
A = ['a', 'b', ... 'N']; // OK
A = ['a']; // Error
A = []; // Error
Is this possible?
You can use rest elements in tuple types to indicate that the tuple type is open-ended and may have zero or more additional elements of the array element type:
type A = [string, string, ...string[]];
The type A must start with two string elements and then it can have any number of string elements after that:
let a: A;
a = ['a', 'b']; // OK
a = ['a', 'b', 'c']; // OK
a = ['a', 'b', 'c', 'd', 'e', 'N']; // OK
a = ['a']; // error! Source has 1 element(s) but target requires 2
a = []; // error! Source has 0 element(s) but target requires 2.
Playground link to code
I have been trying to iterate through an array.
below is the code.
x = ['lemon', 'tea', 'water', ]
def randomShuffle (arr,n):
from random import choices
newList=[]
for item in arr:
r=choices(arr, k=n)
if r.count(item) <= 2:
newList.append(item)
return (newList)
i would like to know the logic for writing it please.
thank you all
Use a while loop: if every item is to appear twice, then teh resulting array should be twice the length of the input one.
And of course check not to add the same item more than twice in the result ;)
Choices return a list of size 1, so I use [0] to get the element
xx = ["a", "b", "c"]
def my_function(x):
res = []
while len(res) < len(x) * 2:
c = choices(x)[0]
if res.count(c) < 2:
res.append(c)
return res
my_function(xx)
> ['c', 'c', 'a', 'b', 'a', 'b']
my_function(xx)
> ['a', 'b', 'b', 'a', 'c', 'c']
I have an array in numpy which looks like this:
myarray = ['a', 'b', 'c', 'd', 'e', 'f']
I would like to return an array of indices for 'b', 'c', 'd' which looks like this:
myind = [1,2,3]
I need this indices array later to use it in a loop. I am using Python 2.7. Thanks folks
You can use np.searchsorted -
In [61]: myarray = np.array(['a', 'b', 'c', 'd', 'e', 'f'])
In [62]: search = np.array(['b', 'c', 'd'])
In [63]: np.searchsorted(myarray, search)
Out[63]: array([1, 2, 3])
If myarray is not alphabetically sorted, we need to use the additional argument sorter with it, like so -
In [64]: myarray = np.array(['a', 'd', 'b', 'e', 'c', 'f'])
In [65]: search = np.array(['b', 'c', 'd'])
In [67]: sidx = np.argsort(myarray)
In [69]: sidx[np.searchsorted(myarray, search, sorter=sidx)]
Out[69]: array([2, 4, 1])
If your array does not contain any duplicates then np.searchsorted should do the trick. if your array contains duplicates then you have to use np.argwhere
Examples:
input_array = np.array(['a','b','c','d','e','f','a'])
search = np.array(['a','b','c'])
np.searchsorted(input_array, search)
output >> array([0, 1, 2])
np.argwhere(input_array == 'a')
output >> array([[0],[6]])
For a more general solution you can do
np.concatenate( (np.argwhere(input_array == 'a') ,
np.argwhere(input_array == 'b'),
np.argwhere(input_array == 'c') ) )
output >> array([[0],[6],[1],[2]])
I need to populate an array, but not by directly counting and splitting the numbers.
I need to do generate the following:
[[a,a,a,a], [a,a,a,b], [a,a,a,c]..... [f,f,f,d], [f,f,f,e], [f,f,f,f]]
And I am struggling to understand it. I realize it should use recursive logic, but I don`t know how to actually build the method.
I would do something like this:
('a'..'f').to_a.repeated_permutation(4).to_a
#=> returns 1296 different combination from ['a','a','a','a'] to ['f','f','f','f']
This should work.
(0...6**4).map do |i|
# Get as base 6
s = i.to_s(6).rjust(4,'0')
# Convert numbers to letters
s.gsub(/[012345]/,'0' => 'a', '1' => 'b', '2' => 'c', '3' => 'd', '4' => 'e', '5' => 'f')
end
Yet another approach:
('aaaa'..'ffff').map(&:chars)
I have an array:
array = ['a', 'b', 'c', 'a', 'b', 'a', 'a']
sorted, just to make it easier to look at:
array = ['a', 'a', 'a', 'a', 'b', 'b', 'c']
I want to remove, for example, three of the a's. array.delete('a') removes every a.
The following code 'works' but I think you'll agree it's absolutely hideous.
new_array = array.sort.join.sub!('aaa', '').split(//)
How do I do this more cleanly?
To give a bit more information on what I'm doing here, I have some strings being pushed into an array asynchronously. Those strings can be (and often are) identical to each other. If there are a certain number of those matching strings, an action is triggered, the matching object is removed (like Tetris, I guess), and the process continues.
Before the following code is run, array could be ['a', 'a', 'a', 'b']:
while array.count(product[:name]) >= product[:quantity]
# trigger an event
product[:quantity].times do
array.slice!(array.index(product[:name]))
end
end
assuming that product[:name] is a and product[:quantity] is 3, after the code above runs, array should be ['b'].
I think you have an XY-problem. Instead of an array, you should use a hash with number of occurrences as the value.
hash = Hash.new(0)
When you want to add an entity, you should do:
hash["a"] += 1
If you want to limit the number to a certain value, say k, then do:
hash["a"] += 1 unless hash["a"] == k
slice may be the thing you're looking for:
3.times {array.slice!(array.index('a'))}
If you want to maintain, or convert, an array so it only one instance of each element, you can use uniq or a Set instead of an array.
array = ['a', 'b', 'c', 'a', 'b', 'a', 'a']
array.uniq # => ["a", "b", "c"]
require 'set'
array.to_set # => #<Set: {"a", "b", "c"}>
A Set will automatically maintain the uniqueness of all the elements for you, which is useful if you're going to have a huge number of potentially repetitive elements and don't want to accumulate them in memory before doing a uniq on them.
#sawa mentioned that this looks like an "XY problem", and I agree.
The source of the problem is using an array instead of a hash as your basic container. An array is good when you have a queue or list of things to process in order but it's horrible when you need to keep track of the count of things, because you have to walk that array to find out how many of a certain thing you have. There are ways to coerce the information you want out of an array when you get the array as your source.
Since it looks like he identified the real problem, here are some building blocks to use around the problem.
If you have an array and want to figure out how many different elements there are, and their count:
array = ['a', 'a', 'a', 'a', 'b', 'b', 'c', 'c']
array_count = array.group_by { |i| i }.map{ |k, v| [k, v.size] }.to_h
# => {"a"=>4, "b"=>2, "c"=>2}
From that point it's easy to find out which ones exceed a certain count:
array_count.select{ |k, v| v >= 3 } # => {"a"=>4}
For a quick way to remove all elements of something from the array, after processing you can use a set "difference" operation:
array = ['a', 'a', 'a', 'a', 'b', 'b', 'c']
array -= ['a']
# => ["b", "b", "c", "c"]
or delete_if:
array.delete_if { |i| i == 'a' }
array # => ["b", "b", "c"]