Javascript: Combining Strings into Array [duplicate] - javascript

This question already has answers here:
Javascript: How to Combine & Filter Arrays
(4 answers)
Closed 5 years ago.
I have 3 strings that I need to convert into a single array, from there I want to filter out the type: "bundle".
I need to note that I'm using Javascript Code by Zapier and their javascript library is a bit limited as far as the functions that I can use, but this is what I have so far which works if I hard code itemArray. I'm just having trouble creating my itemArray from the 3 given strings:
Strings:
var type = 'bundle, simple, simple';
var name = 'Product1, Product2, Product3';
var price = '1.99, 2.99, 3.99';
I need to figure out how to convert the above 3 strings above into the following array using javascript:
var itemArray = [
{type:"bundle", info: {name: "Product1", price: "1.99"}},
{type:"simple", info: {name: "Product2", price: "2.99"}},
{type:"simple", info: {name: "Product3", price: "3.99"}}];
From there I'm looking to filter out the bundle product type and only return the simple product types, I'm doing that with the following code:
// Using a for loop
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
var item = itemArray[i];
if (item.type == 'simple') filtered.push(item);
}
return {filtered}; //this returns just the 2 simple product type arrays
So my question is, how do I take those 3 strings that I began with and convert those into my itemArray format using javascript?

First make the strings into arrays of the three strings you want. Then in a for loop you can push all of them in whatever (identical) format you want, since all 3 lists have 3 elements each. then you can use the filter function to easily filter out the bundle elements as below.
The following snippet will print out the item array and the filtered value you requested
var types = 'bundle, simple, simple'.split(", ");
var names = 'Product1, Product2, Product3'.split(", ");
var prices = '1.99, 2.99, 3.99'.split(", ");
var itemArray = [];
for(var i = 0; i < 3; i++){
itemArray.push({"type": types[i], "info":{"name": names[i], "price": prices[i]}});
}
console.log(itemArray);
var filtered = [];
for (var i = 0; i < itemArray.length; ++i) {
var item = itemArray[i];
if (item["type"] === 'simple') filtered.push(item);
}
console.log({filtered});

var type = 'bundle, simple, simple'.split(', '), // split the
nameArr = 'Product1, Product2, Product3'.split(', '), // strings to
priceArr = '1.99, 2.99, 3.99'.split(', '), // get the arrays
res = type.map((v,i) => Object.assign({}, {type: v, info: {name: nameArr[i], price: priceArr[i]}})), //map the objects with specified keys and values from given arrays
result = res.filter(v => v.type != 'bundle'); //remove the `bundle` type elements
console.log(result);

Related

Take String From Javascript Array [duplicate]

This question already has answers here:
using .join method to convert array to string without commas [duplicate]
(4 answers)
Convert array to string javascript by removing commas [duplicate]
(3 answers)
Closed 1 year ago.
I have an input field with one button. I store value of input in array.
My console.log output has below result
How can take the String "JOHN" from this array?
My code is:
var category = $('#customer_name_search').val();
var len = category.length;
var arr = [];
for(var i=0; i<len; i++){
var test = category[i];
arr.push(test);
}
console.log(arr);
You might want to use the join() method
var category = $('#customer_name_search').val();
var len = category.length;
var arr = [];
for(var i=0; i<len; i++){
var test = category[i];
arr.push(test);
}
console.log(arr.join(''));
here is some documentation
Use Array.Join().
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/join
const elements = ['Fire', 'Air', 'Water'];
console.log(elements.join());
// expected output: "Fire,Air,Water"
console.log(elements.join(''));
// expected output: "FireAirWater"
console.log(elements.join('-'));
// expected output: "Fire-Air-Water"
you can use array.join to merge the strings in an array
const array = ["J", "O", "H", "N"];
const merged = array.join("");
so the result will be "JOHN"
You just need to join the array by using array function(join).
Check out this link
var category = $('#customer_name_search').val();
var str = category.join('');

How to get unique values from two 2D arrays in JavaScript

I am trying to get unique values from two arrays which looks like that:
array[{A,B,C},{C,D,E},{1,3,2},....]
both looks the same.
I tried to add them using concat and the get unique values from looping.
So I ended up with this:
function uniqueValues() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var srcSheet = ss.getSheetByName("arr1");
const array1 = srcSheet.getRange(1, 1, srcSheet.getLastRow(), srcSheet.getLastColumn()).getValues();
var srcSheet1 = ss.getSheetByName("arr2");
const array2 = srcSheet1.getRange(1, 1, srcSheet1.getLastRow(), srcSheet1.getLastColumn()).getValues();
var dodaj = array1.concat(array2);
for (var i=0; i<dodaj.length; i++) {
var listI = dodaj[i];
loopJ: for (var j=0; j<dodaj.length; j++) {
var listJ = dodaj[j];
if (listI === listJ) continue;
for (var k=listJ.length; k>=0; k--) {
if (listJ[k] !== listI[k]) continue loopJ;
}
dodaj.splice(j, 1);
}
}
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, 3).setValues(dodaj);
//Logger.log(dodaj);
}
It was working well when array looked like this array[{A,B},{C,D}] but with three elements it started to return duplicates as well... I have no idea what can be wrong.
If I understand you correctly, you want to retrieve the unique rows from the values in arr1 and arr2. That is to say, you want to remove duplicate inner arrays from dodaj.
After using concat to merge the two arrays, you could do the following:
Use JSON.stringify() to transform each inner array to a string, in order to compare them without iterating through them.
Use the Set constructor and the spread syntax in order to remove the duplicate strings (see this answer).
Transform the strings back to arrays with JSON.parse().
Code snippet:
var dodaj = array1.concat(array2);
dodaj = [...new Set(dodaj.map(JSON.stringify))].map(JSON.parse);
var result = ss.getSheetByName("test").getRange(2, 5, dodaj.length, dodaj[0].length).setValues(dodaj);

Javascript - more efficent way to "map" two arrays together

I have two object arrays (which I receive from a server based on some user input):
array1 = [{id:1, name:Bob}, {id:2, name:John}, {id:3, name:Mary}];
array2 = [{id:2, field:true},{id:2, field:true}, {id:3, field:false}];
The id's in both array correspond to each other (they are user ids). In real life these arrays will be much larger (up to 8000 elements in array 1, and 16000 in array2).
The thing I need to accomplish is on the front end I am currently showing just array2 information which displays to the user id and the field. The problem is the front end user doesn't know anyone by their user id instead they know them by their name. I need an array which has objects which look like this: {id:'',name:'',field:''}.
My first thought was to create a new array and "combine the two arrays" :
var new_array = [];
for (var i = 0; i < array2.length; i++) {
var name = 'Unknown';
for (var j = 0; j < array1.length; j++) {
if (array1[j].id === array2[i].id) {
name = array1[j].name;
}
this.new_array.push({
id: array2[i].id,
name: name,
field: array1[j].field
});
}
}
So I loop through the the second array and check if the id matches the id of the first array. If it does I take the name from the first array and that is the user's name so that is how I get the user's name.
This works, but it is kind of slow on the front end, it take a few seconds to do this and if there are many items the user experience doesn't feel good there is a lot of waiting. I am looking for a more efficient way to do what I need to do.
Run through one array and create an object to map id values to entries:
var array2idx = array2.reduce(function(map, value) {
map[value.id] = value;
return map;
}, {});
Now you can find the array2 values with a simple lookup:
var new_array = [];
for (var i = 0; i < array1.length; i++) {
var v2 = array2idx[array1[i].id];
if (v2) {
new_array.push({
id: v2.id,
name: array1[i].name,
field: array1[i].field
});
}
}
That should be considerably faster. Looking up an id in the index object will take almost no time at all.

Combining elements of 2 dimentional array

I have an JavaScript array:
var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];
I want final array to look like:
var final = [["A",[["05",90],["04",240],["03",235]]],["B",[["00",123],["01",234]]]];
The final array is formed by combining all the 2nd element of 2 dimensional array when the 1st element matches.
Please advice how can this be achieved in JavaScript
Object keys are generally the easiest way to create groups like this
var tmp = {}; // temporary grouping object
// loop over data
arr.forEach(function (item) {
// check if group started
if (!tmp.hasOwnProperty(item[0])) {
tmp[item[0]] = [];
}
// push data to group
tmp[item[0]].push(item[1]);
});
// map temp object to results array
var results = Object.keys(tmp).map(function (key) {
return [key, tmp[key]];
});
DEMO
If you start with the array you gave:
var arr = [["A",["05",90]],["A",["04",240]],["A",["03",235]],["B",["00",123]],["B",["01",234]]];
then create a new array to store the values:
var final = [];
and simply combine all of the third-level elements (such as ["05",90] and ["01",234]) of each second-level ones (such as "A" and "B") by looping through the array:
for(var i = 0; i < arr.length; i++) {
var found = false;
for(var j = 0; j < final.length; j++) {
if(arr[i][0] == final[j][0]) {
final[j][1].push(arr[i][1]);
found = true;
break;
}
}
if(!found) {
final[final.length] = [arr[i][0], [[arr[i][1][0], arr[i][1][1]]]];
}
}
This is essentially a sorting method: if the "key" is equal to one in the final array, then it adds it to that one. If not, then appends it to the end of final.
Here's the working example on JSFiddle: link.
This outputs the array:
["A", [["05", 90], ["04", 240], ["03", 235]]], ["B", [["00", 123], ["01", 234]]]
as requested.
Also, as #PaulS commented, it would be recommended to use Objects instead as Strings, to make them Key-Value pairs. But in my answer I stuck with arrays.

What kind of array is this in JavaScript?

I have an array that looks like this:
var locationsArray = [['title1','description1','12'],['title2','description2','7'],['title3','description3','57']];
I can't figure out what type of array this is. More importantly, I'm gonna have to create one based on the info there. So, if the number on the end is greater than 10 then create a brand new array in the same exact style, but only with the title and description.
var newArray = [];
// just a guess
if(locationsArray[0,2]>10){
//add to my newArray like this : ['title1','description1'],['title3','description3']
?
}
How can I do it?
Try like below,
var newArray = [];
for (var i = 0; i < locationsArray.length; i++) {
if (parseInt(locationsArray[i][2], 10) > 10) {
newArray.push([locationsArray[i][0], locationsArray[i][1]]);
}
}
DEMO: http://jsfiddle.net/cT6NV/
It's an array of arrays, also known as a 2-dimensional array. Each index contains its own array that has its own set of indexes.
For instance, if I retrieve locationsArray[0] I get ['title1','description1','12']. If I needed to get the title from the first array, I can access it by locationsArray[0][0] to get 'title1'.
Completing your example:
var newArray = [];
// just a guess
if(locationsArray[0][2]>10){
newArray.push( [ locationsArray[0][0], locationsArray[0][1] ] );
}
throw that in a loop and you're good to go.
It's an array of arrays of strings.
Each time there is this : [], it defines an array, and the content can be anything (such as another array, in your case).
So, if we take the following example :
var myArray = ["string", "string2", ["string3-1", "string3-2"]];
The values would be as such :
myArray[0] == "string"
myArray[1] == "string2"
myArray[2][0] == "string3-1"
myArray[2][1] == "string3-2"
There can be as many levels of depth as your RAM can handle.
locationsArray is an array of arrays. The first [] operator indexes into the main array (e.g. locationsArray[0] = ['title1','description1','12']) while a second [] operation indexes into the array that the first index pointed to (e.g. locationsArray[0][1] = 'description1').
Your newArray looks like it needs to be the same thing.
It's an array of array.
var newArray = [];
var locationsArray = [
['title1','description1','12'],
['title2','description2','7'],
['title3','description3','57']
];
for(i = 0; i < locationsArray.length; i++) {
if (locationsArray[i][2] > 10) {
newArray .push([locationsArray[i][0], locationsArray[i][1]]);
}
}
console.log(newArray );

Categories

Resources