How to use mapping to transfer things to an empty array? - javascript

I am trying to pass over the function that is inside of the variable inputOne to the empty array of transferHere
This does not seem to be working. How can I map what is inside of inputOne into transferHere, so that everything is transferred over?
var transferHere = [];
var inputOne = transferHere.map(function(name) {
return (5 * name) - 20;
});

The map function iterates over an array of values and generates a new array of values.
For example:
var arr1 = [1,2,3];
var result = arr1.map(function(val){
return val + 1;
});
//result would be: [2,3,4]
So it seems like you are doing it wrong and your code should be (assuming that
inputOne is an array):
var transferHere= inputOne.map(function(name) {
return (5 * name) - 20;
});
UPDATE:
From the comment i understand that inputOne is a function and you want to put it's actual content (i.e. as a string) in an array, so here is how:
var arr1 = [];
arr1.push(inputOne.toString());

Related

Javascript: Inserting data from an array into function parameter

I have only been learning javascript for 2 weeks, so apologies if my question seems weird/doesn't make sense. I'm learning the basics of arrays, and to help me learn I like to practise and play around with the code but I can't seem to figure this one out.
I've created a simple function, and wanting to call upon the function to calculate the sum of variables in an array. Here is my code below:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc([0],[1]);
alert("The total is " + total);
Can anyone please shed any light as to how I input the numbers "12" and "567" into the function parameters? The result here as it stands outputs to "01"
Thanks
You have two options:
Your option but, it is very limited to only two values.
You need to pass reference to your array elements like so (myArray[0], myArray[1])
Create new function - let's call it sumValuesInArray(), pass an array and calculate all values inside an array using for loop.
See working example here:
//functions
function simpleCalc (a,b) {
var result = a + b;
return result;
}
//array
var myArray = [12,567];
//final calculation
var total = simpleCalc(myArray[0],myArray[1]);
//alert("The total is " + total);
// OR
function sumValuesInArray(array) {
var total = 0;
for(i = 0; i < array.length; i++) {
var element = array[i];
total += element;
}
return total;
}
console.log(sumValuesInArray(myArray));
You don't specify the array but only indexes :
var total = simpleCalc([0],[1]);
So, it passes two array objects : [0] and [1].
The concatenation of them here :
var result = a + b;
has as result the 01 String.
To pass the two first elements of myArray, try it :
var total = simpleCalc(myArray[0],myArray[1]);
You need to access the array values by index. You do this using the brackets WITH the name of the array. If you pass the brackets with numbers inside, you're creating new arrays.
It should be:
var total = simpleCalc(myArray[0],myArray[1]);

How to remove partial duplicate values in jquery array

I have a single level array of key/value pairs, like this:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square']
I need a function to perform the following:
find all duplicate keys
replace the first occurrence of the key/value pair with the second occurrence
delete the second occurrence
In this case, it would produce the following result:
user_filters= ['color=blue', 'size=large', 'shape=square']
Something like...
function update_array(){
$.each(user_filters, function(i){
var key = this.split('=')[0];
if(key is second occurrence in user_filters)
{
var index = index of first occurrence of key
user_filters[index] = user_filters[i];
user_filters.splice(i,1);
}
});
}
What is the best way to do this? Thanks!
I would keep the data in an object and this way any duplicate will automatically overwrite the previous entry..
See this for example:
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var object = {};
for (var i = 0; i < user_filters.length; i++) {
var currentItem = user_filters[i].split('=');
var key = currentItem[0];
var value = currentItem[1];
object[key] = value;
}
console.log(object);
You can use a hash object to get the key-value pairs without duplicates and then transform the hash object back into an array like this:
function removeDuplicates(arr) {
var hash = arr.reduce(function(h, e) {
var parts = e.split("=");
h[parts[0]] = parts[1];
return h;
}, {});
return Object.keys(hash).map(function(key) {
return key + "=" + hash[key];
});
}
var user_filters = ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
console.log(removeDuplicates(user_filters));
You could use a Map which does the unique/overriding automatically, and is able to get you an array back in case you need it
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
var m = new Map(user_filters.map(v => v.split("=")));
console.log([...m.entries()].map(v => v.join("=")));
It would be better to iterate from back of array ,
thus for every unique key you need to keep a variable true or false (initially false).
so if true mean already occurred so deleted it else keep it and make its variable true .
It is much more better approach then your current . you don't have to keep last index and swapping then deleting.
You may convert to json and then back to the array format you want . IN the below code you get the result object in the format you want.
var user_filters= ['color=blue', 'size=small', 'shape=circle', 'size=large', 'shape=square'];
function toJson(obj){
var output = {};
$.each(obj, function(i){
var keyvalPair = this.split('=')
var key = keyvalPair[0];
output[key]= keyvalPair[1];
});
return output;
}
function toArray(obj){
var output = [];
$.each(obj, function(i){
output.push(i+"="+obj[i]);
});
return output;
}
var result = toArray(toJson(user_filters));
console.log(result);

Javascript sorting input values into an array

I have the below code which looks at hidden inputs with the class howmanyproducts.
$("#proddiv .howmanyproducts").each(function() {
var idval = $(this.id).val();
});
What I am trying to achieve is for each id get the value and sort the ids into an array based on their values.
You have to add both your ids and the corresponding values to an array, then to use the sort method of your array with an adapted compare function. Let say your values are number but are retrieved as string :
// Create a new empty array :
var ids = [];
$("#proddiv .howmanyproducts").each(function() {
var id = this.id;
var val = $(this.id).val();
// Store the id and the value:
ids.push([id, +val]);
});
// Sort the array in place, using the second element of each item
// ie. the value :
ids.sort(function(a, b) { return a[1] - b[1]; });
// Once sorted, make a new array with only the ids:
var result = ids.map(function(a,b) { return a[0] });
I used the traditional syntax, but note that it can be written more simply using arrow functions:
ids.sort((a,b) => a[1] - b[1]);
var result = ids.map((a,b) => a[0]);
var arrayOfValues = [];
$("#proddiv .howmanyproducts").each(function() {
arrayOfValues.push($(this).val());
}

How to set hash key dynamically in javascript

With this code,
h = {}
for (var i in [0,1]){ h[i.ToString] = i; }
I expected same result with h["1"] = 1 and h["2"] = 2.
Why is this code doesn't work, and how can I define hash key dynamically in javascript?
The for .. in loop in JS iterates over keys, not over values (https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in).
So in your case, you iterate over the keys of the array you have in there.
Those will be 0, 1, 2 ... no matter what you put in there.
What you could do instead would be something like this:
var obj = {};
var data = [1,2,3,4];
data.forEach(function(val) {
obj[val] = val;
});

Another javascript array challenge

Solving another array manipulation, and I'm taking longer than usual to solve this. I need help in combining array values:
var array1 = ["alpha|LJ", "bravo|MH", "charlie|MH", "delta|MF",
"echo|16", "{foxtrot}|GG", "{golf}|HS"];
var array2 = ["charlie-{golf}-{foxtrot}", "echo-{golf}"]; //some templates
such that the final array be:
final_array = ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF",
"echo-HS-16"];
To make it clear how I arrived with the final_array, alpha, bravo and delta only got their "|" replaced with "-" since they are not found on my array2 template. charlie and echo got the template so the respective values of the {} were replaced based on array1. Array1 honestly is not the best key:value relationship that I could come up for now.
Here are some requirementL:
* Anything in array1 with {} braces are not meant to be templated.
* Keywords in array2 will always have a matching value in array1.
I've read about jquery .map() and thinking that it is achievable using this, maybe together with Regexp. Hope you'll utilize these. Also, if it helps, final_array can be of any order.
I really need to up my knowledge on these two topics... :|
Thank you in advance.
Edit: Updated to match your output and comment some of the madness. This doesn't feel like it's the most efficient, given the split() done to values at the start and then again at the end...but it works.
function funkyTransform( values, templates ){
// Make a copy of the array we were given so we can mutate it
// without rudely changing something passed to our function.
var result = values.concat();
// Map {value} entries for later lookup, and throw them out of the result
var valueMap = {};
for (var i=result.length-1;i>=0;--i){
var pair = result[i].split('|');
if (pair[0][0]=="{"){
valueMap[pair[0]] = pair[1];
result.splice(i,1); // Yank this from the result
}
}
console.log(valueMap);
// {
// "{foxtrot}": "GG",
// "{golf}": "HS"
// }
// Use the value map to replace text in our "templates", and
// create a map from the first part of the template to the rest.
// THIS SHOULD REALLY SCAN THE TEMPLATE FOR "{...}" PIECES
// AND LOOK THEM UP IN THE MAP; OOPS O(N^2)
var templateMap = {};
for (var i=templates.length-1;i>=0;--i){
var template = templates[i];
for (var name in valueMap){
if (valueMap.hasOwnProperty(name)){
template = template.replace(name,valueMap[name]);
}
}
var templateName = template.split('-')[0];
templateMap[ templateName ] = template.slice(templateName.length+1);
}
console.log(templateMap);
// {
// "charlie": "HS-GG",
// "echo": "HS"
// }
// Go through the results again, replacing template text from the templateMap
for (var i=result.length-1;i>=0;--i){
var pieces = result[i].split('|');
var template = templateMap[pieces[0]];
if (template) pieces.splice(1,0,template);
result[i] = pieces.join('-');
}
return result;
}
var output = funkyTransform( array1, array2 );
console.log(output);
// ["alpha-LJ", "bravo-MH", "charlie-HS-GG-MH", "delta-MF", "echo-HS-16"]
This managed to get your desired output, though I made a few assumptions:
Anything in array1 with {} braces are not meant to be templated.
Keywords in array2 will always have a matching value in array1 (this can easily be changed, but not sure what your rule would be).
Code:
// This is the main code
var final_array = $.map(array1, function (item) {
var components = item.split('|');
// Ignore elements between {} braces
if (/^\{.*\}$/.test(components[0])) return;
components[0] = template(components[0]);
return components.join('-');
});
// Helper to lookup array2 for a particular string and template it
// with the values from array1
function template(str) {
var index = indexOfMatching(array2, str, '-');
if (index == -1) return str;
var components = array2[index].split('-');
var result = [str];
for (var i = 1; i < components.length; i++) {
result.push(array1[indexOfMatching(array1, components[i], '|')]
.split('|')[1]);
}
return result.join('-');
}
// Helper to for looking up array1 and array2
function indexOfMatching(array, target, separator) {
for (var i = 0; i < array.length; i++) {
if (array[i].split(separator)[0] === target) return i;
}
return -1;
}

Categories

Resources