Using split/join to replace a string with an array - javascript

I'm trying to replace the value of item with values ​​in the array arr, but I only get that if I use: arr [1], arr [2] ... if I just let
arr, returns abcdefg.
I am PHP programmer, and I have a minimal
notion with JavaScript, can someone give me a light?
var item = 'abcdefg';
var arr = new Array();
arr[1] = "zzz";
arr[2] = "abc";
var test = item.split(arr);
alert(test.join("\n"));

Use:
var item = 'Hello, 1, my name is 2.';
var arr = new Array();
arr [1] = 'admin';
arr [2] = 'guest';
for (var x in arr)
item = item.replace(x, arr[x]);
alert(item);
It produces:
Hello, admin, my name is guest.

Split uses regular expressions, so
"My String".split('S') == ["My ","tring"]
If you are trying to replace a string:
"abcdef".replace('abc','zzz') == "zzzdef"

Related

Javascript check if any of the values exist on array of objects [duplicate]

I have one array like this one:
array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}]
I have a second array of integer :
array2=[1,3]
I would like to obtain this array without a loop for :
arrayResult = ['value1', 'value3']
Does someone know how to do it with javascript ?
Thanks in advance
Map the elements in array2 to the label property of the element in array1 with the corresponding value:
array2 // Take array2 and
.map( // map
function(n) { // each element n in it to
return array1 // the result of taking array1
.find( // and finding
function(e) { // elements
return // for which
e.value // the value property
=== // is the same as
n; // the element from array2
}
)
.label // and taking the label property of that elt
;
}
)
;
Without comments, and in ES6:
array.map(n => array1.find(e => e.value === n).label);
You can use .filter and .map, like this
var array1 = [
{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}
];
var array2 = [1, 3];
var arrayResult = array1.filter(function (el) {
return array2.indexOf(el.value) >= 0;
}).map(function (el) {
return el.label;
});
console.log(arrayResult);
A simple for-loop should suffice for this. In the future you should seriously post some code to show what you have tried.
var array1=[{value:1, label:'value1'},{value:2, label:'value2'}, {value:3, label:'value3'}];
var array2=[1,3];
var result = [];
for (var i = 0; i < array2.length; i++){
result.push(array1[array2[i]-1].label);
}
console.log(result); //["value1", "value3"]
JSBIN
Good answers all. If I may suggest one more alternative using Map as this seems to be suited to a key:value pair solution.
var arr1 = [ {value:1, label:'value1'}, {value:2, label:'value2'}, {value:3, label:'value3'} ];
var arr2 = [1, 3];
// create a Map of the first array making value the key.
var map = new Map( arr1.map ( a => [a.value, a.label] ) );
// map second array with the values of the matching keys
var result = arr2.map( n => map.get ( n ) );
Of course this supposes that the key:value structure of the first array will not become more complex, and could be written in the simpler form of.
var arr1 = [[1,'value1'], [2,'value2'], [3,'value3']]; // no need for names
var arr2 = [1, 3];
var map = new Map( arr1 ); // no need to arr1.map ;
var result = arr2.map( n => map.get ( n ) );
Just index the first array using the _.indexBy function:
var indexedArray1 = _.indexBy(array1, "value");
_.map(array2, function(x) { return indexedArray1[x].label; });

Split an array cause an error: not a function

I want to split an array that already have been split.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(',');
var array_s = array_dt.split('|');
console.log(array_s);
That code returns TypeError: array_dt.split is not a function.
I'm guessing that split() can not split an array. Have I wrong?
Here's how I want it to look like. For array_dt: 2016-08-08,2016-08-07,2016-08-06,2016-08-05,2016-08-04. For array_s: 63,67,64,53,63. I will use both variables to a chart (line) so I can print out the dates for the numbers. My code is just as example!
How can I accomplish this?
Demo
If you want to split on both characters, just use a regular expression
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
console.log(array_dt)
This will give you an array with alternating values, if you wanted to split it up you can do
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = string.split(/[,|]/);
var array1 = array_dt.filter( (x,i) => (i%2===0));
var array2 = array_dt.filter( (x,i) => (i%2!==0));
console.log(array1, array2)
Or if you want to do everything in one go, you could reduce the values to an object
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/).reduce(function(a,b,i) {
return a[i%2===0 ? 'dates' : 'numbers'].push(b), a;
}, {numbers:[], dates:[]});
console.log(array)
If performance is important, you'd revert to old-school loops, and two arrays
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array = string.split(/[,|]/);
var array1 = [];
var array2 = [];
for (var i = array.length; i--;) {
if (i % 2 === 0) {
array1.push(array[i]);
} else {
array2.push(array[i]);
}
}
console.log(array1, array2)
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var array_dt = [];
var array_s = [];
string.split('|').forEach(function(el){
var temp = el.split(",");
array_dt.push(temp[0]);
array_s.push(temp[1]);
});
console.log(array_dt);
console.log(array_s);
Just do it one step at a time - split by pipes first, leaving you with items that look like 2016-08-08,63. Then for each one of those, split by comma, and insert the values into your two output arrays.
var string = '2016-08-08,63|2016-08-07,67|2016-08-06,64|2016-08-05,53|2016-08-04,63';
var arr = string.split("|");
var array_dt = [];
var array_s = [];
arr.forEach(function(item) {
var x = item.split(",");
array_dt.push(x[0]);
array_s.push(x[1]);
});

how to push a list of number into an array using javascript

suppose I have printed a list of values and stored in a variable.The variable is of string type.Now I need to push those elements stored in a variable into an array.How can do this using javascript?
private var data : String;
private var dataarray:Array;
for(var k : int = 0; k < StockItemsProperties_list.Count; k++)
{
data=StockItemsProperties_list[k].InnerText+"\t";
dataarray=new Array();
dataarray.Push(data);
Debug.Log("Elements in the array"+dataarray);
}
String.prototype.split() && Array.prototype.concat()
var arr = ["xyz"];
var str1 = "foo,bar,baz";
var str2 = "qwer";
with non-empty string separator:
var str1_separated = str1.split(",");
// str1_separated == ["foo","bar","baz"]
with empty string separator:
var str2_separated = str2.split("");
// str2_separated == ["q","w","e","r"]
pushing new values to array:
arr.concat(str1_separated, str2_separated);
// arr == ["xyz","foo","bar","baz","q","w","e","r"]
If I understand you correctly then you are looking for something like this.
var x = "abc"
var y = "lmn"
var array =[]
array[0]= x;
array[1]= y;
the array will contain ["abc", "lmn"].
If your question is that you have saved all the values in the same var then as #Midhun said you need a delimiter example
var x = "abc,lmn"
array=x.split(',')
here I am using , as a delimiter
Hope that helps.
Hope you have stored the values in a variable using some symbol to sepreate the items . If so you can use the javascript split() to convert string to list of items. The Split function will return you an array with the list of items
Please have look at the below url http://www.w3schools.com/jsref/jsref_split.asp
Declare the Variable which you want to push int in array.
var array= [];
var a = +1;
var b = +2;
var c = +3;
array[0]=a;
array[1]=b;
array[2]=c;

Group array items based on variable javascript

I have an array that is created dynamic from an xml document looking something like this:
myArray[0] = [1,The Melting Pot,A]
myArray[1] = [5,Mama's MexicanKitchen,C]
myArray[2] = [6,Wingdome,D]
myArray[3] = [7,Piroshky Piroshky,D]
myArray[4] = [4,Crab Pot,F]
myArray[5] = [2,Ipanema Grill,G]
myArray[6] = [0,Pan Africa Market,Z]
This array is created within a for loop and could contain whatever based on the xml document
What I need to accomplish is grouping the items from this array based on the letters so that all array objects that have the letter A in them get stored in another array as this
other['A'] = ['item 1', 'item 2', 'item 3'];
other['B'] = ['item 4', 'item 5'];
other['C'] = ['item 6'];
To clarify I need to sort out items based on variables from within the array, in this case the letters so that all array objects containing the letter A goes under the new array by letter
Thanks for any help!
You shouldn't use arrays with non-integer indexes. Your other variable should be a plain object rather than an array. (It does work with arrays, but it's not the best option.)
// assume myArray is already declared and populated as per the question
var other = {},
letter,
i;
for (i=0; i < myArray.length; i++) {
letter = myArray[i][2];
// if other doesn't already have a property for the current letter
// create it and assign it to a new empty array
if (!(letter in other))
other[letter] = [];
other[letter].push(myArray[i]);
}
Given an item in myArray [1,"The Melting Pot","A"], your example doesn't make it clear whether you want to store that whole thing in other or just the string field in the second array position - your example output only has strings but they don't match your strings in myArray. My code originally stored just the string part by saying other[letter].push(myArray[i][1]);, but some anonymous person has edited my post to change it to other[letter].push(myArray[i]); which stores all of [1,"The Melting Pot","A"]. Up to you to figure out what you want to do there, I've given you the basic code you need.
Try groupBy function offered by http://underscorejs.org/#groupBy
_.groupBy([1.3, 2.1, 2.4], function(num){ return Math.floor(num); });
Result => {1: [1.3], 2: [2.1, 2.4]}
You have to create an empty JavaScript object and assign an array to it for each letter.
var object = {};
for ( var x = 0; x < myArray.length; x++ )
{
var letter = myArray[x][2];
// create array for this letter if it doesn't exist
if ( ! object[letter] )
{
object[letter] = [];
}
object[ myArray[x][2] ].push[ myArray[x] ];
}
Demo fiddle here.
This code will work for your example.
var other = Object.create(null), // you can safely use in opeator.
letter,
item,
max,
i;
for (i = 0, max = myArray.length; i < max; i += 1) {
item = myArray[i];
letter = myArray[2];
// If the letter does not exist in the other dict,
// create its items list
other[letter] = other[letter] || [];
other.push(item);
}
Good ol' ES5 Array Extras are great.
var other = {};
myArray.forEach(function(n, i, ary){
other[n[2]] = n.slice(0,2);
});
Try -
var myArray = new Array();
myArray[0] = [1,"The Melting Pot,A,3,Sake House","B"];
myArray[1] = [5,"Mama's MexicanKitchen","C"];
myArray[2] = [6,"Wingdome","D"];
myArray[3] = [7,"Piroshky Piroshky","D"];
myArray[4] = [4,"Crab Pot","F"];
myArray[5] = [2,"Ipanema Grill","G"];
myArray[6] = [0,"Pan Africa Market","Z"];
var map = new Object();
for(i =0 ; i < myArray.length; i++){
var key = myArray[i][2];
if(!map[key]){
var array = new Array();
map[key] = array;
}
map[key].push(myArray[i]);
}

How do I divide a complex string into 3 seperate arrays?

Here's where I am:
I started with an array...cleaned it up using 'regex'.
Now I have this...each item has three values
mystring = 4|black|cat, 7|red|dog, 12|blue|fish
Here's where I want to be:
I want to end up with three arrays.
array1=("4","7","12")
array2=("black","red","blue")
array3=("cat","dog","fish")
I also want to do this without leaving the page...preferably using javascript
I understand the theory, but I'm getting tangled in the syntax.
I'd use John Resig's famous "search and don't replace" method here, it's perfect for it:
var arr1 = [], arr2 = [], arr3 = [],
mystring = "4|black|cat, 7|red|dog, 12|blue|fish";
mystring.replace(/(\d+)\|([^\|]+)\|([^,]+)/g, function ($0, $1, $2, $3) {
arr1.push($1);
arr2.push($2);
arr3.push($3);
});
Example
You want to use the split() method :
var res = mystring.split(','); //will give you an array of three strings
var subres = res[0].split('|'); //will give you an array with [4, black, cat]
//etc...
Like this?:
var values = mystring.split(',');
var arrays = new Array();
for(var i=0; i < values.length; i++) {
var parts = values[i].split('|');
for(var j = 0; j < parts.length;j++) {
if(!arrays[j]) {
arrays[j] = new Array();
}
arrays[j].push(parts[j]);
}
}
Will give you an array that contains those three arrays.
var str = '4|black|cat, 7|red|dog, 12|blue|fish';
var tmp = str.split(',');
var firstArray = Array();
var secondArray = Array();
var thirdArray = Array();
for( var i in tmp ){
var splitted = tmp[i].split('|');
//alert(true);
firstArray[i]=splitted[0];
secondArray[i]=splitted[1];
thirdArray[i]=splitted[2];
}

Categories

Resources