How to split array values using angularjs? - javascript

How to split array values using 'angularjs.split' method? It is not working here:
var items =["Regular Servicing & Maintenance","Faults (Interior & Exterior)"];
console.log(items.split(',');

Well, your question is confusing on a number of levels. For one, there isn't an AngularJS function that I'm seeing in the documentation for split.
There's a JavaScript method called split(), but it's used to split a string into an array of substrings, per the linked documentation.
For another, you're already instantiating the items variable with an array of strings though, so you're not really going to get anything from that that you don't already have in the initial value.
Split Method
Now, if you had a string like the following example, you could split that by the commas and yield an array similar to what you've got in your question:
var str = "Apples, Bananas, Cherries";
var arr = str.split(', '); //Note the space as well
console.log(arr); //Yields ["Apples", "Bananas", "Cherries"]
Join Method
But if you're looking for the inverse and you're rather looking to join these into a comma-separated string, you might look at the join() JavaScript method that would look like the following (continued from above):
var result = arr.join(', '); //Note the space again
console.log(result); //Apples, Bananas, Cherries
IndexOf Method
To match the comment you left after I posted this though, if you're looking for the index value of the array that matches a given string, look at the indexOf() method, per the following (again, building from the above example):
var index = arr.indexOf('Bananas'); //Yields 1
var indexRes = arr[index]; //Yields 'Bananas'
If you're looking for something else, you're going to need to clarify the original question.

The below code represents JavaScript code
var items = ["Regular Servicing & Maintenance", "Faults (Interior & Exterior)"];
for (var i = 0; i < items.length; i++) {
console.log("Input:-" + items[i])
console.log("Output:-" + items[i].split('&'));
}
Input: -Regular Servicing & Maintenance
Output: -Regular Servicing, Maintenance
Input: -Faults(Interior & Exterior)
Output: -Faults(Interior, Exterior)
How to split array values using angularJs
$scope.items = [{
'item': 'Regular Servicing & Maintenance'
}, {
'item': 'Faults (Interior & Exterior)'
}]
$scope.array = [];
angular.forEach($scope.items, function(value, key) {
var splitLength = value.item.split('&').length;
for (var i = 0; i < splitLength; i++) {
$scope.array.push(value.item.split('&')[i]);
}
});
console.log($scope.array)

Related

String into multiple string in an array

I have not been coding for long and ran into my first issue I just can not seem to figure out.
I have a string "XX|Y1234$ZT|QW4567" I need to remove both $ and | and push it into an array like this ['XX', 'Y1234', 'ZT', 'QW4567'].
I have tried using .replace and .split in every way I could like of
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for(i = o; i <array.length; i++)
var loopedArray = array[i].split("|")
loopedArray.push(array2);
}
I have tried several other things but would take me awhile to put them all down.
You can pass Regex into .split(). https://regexr.com/ is a great tool for messing with Regex.
// Below line returns this array ["XX", "Y1234", "ZT", "QW4567"]
// Splits by $ and |
"XX|Y1234$ZT|QW4567".split(/\$|\|/g);
Your code snippet is close, but you've messed up your variables in the push statement.
var array = "XX|Y1234$ZT|QW4567"
var array2 = [];
array = array.split("$");
for (i = 0; i < array.length; i++) {
var loopedArray = array[i].split("|")
array2.push(loopedArray);
}
array2 = array2.flat();
console.log(array2);
However, this can be rewritten much cleaner using flatMap. Also note the use of let instead of var and single quotes ' instead of double quotes ".
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array
.split('$')
.flatMap(arrayI => arrayI.split('|'));
console.log(array2);
And lastly, split already supports multiple delimiters when using regex:
let array = 'XX|Y1234$ZT|QW4567'
let array2 = array.split(/[$|]/);
console.log(array2);
You can do this as follows:
"XX|Y1234$ZT|QW4567".replace('$','|').split('|')
It will produce the output of:
["XX", "Y1234", "ZT", "QW4567"]
If you call the split with two parameters | and the $ you will get an strong array which is splittend by the given characters.
var array = "XX|Y1234$ZT|QW4567";
var splittedStrings = array.Split('|','$');
foreach(var singelString in splittedStrings){
Console.WriteLine(singleString);
}
the output is:
XX
Y1234
ZT
QW4567

Array values to a string in loop

I have an object (key value pair) looks like this
I want to get a string of '[100000025]/[100000013]'
I can't use var str = OBJ[0].PC + OBJ[1].PC (which gives me '100000025100000013')
because I need the bracket structure.
The number of items can vary.
Added >> Can it be done without using arrow function?
const string = array.map(({PC}) => `[${PC}]`).join('/')
You could map every string to the string wrapped in brackets, then join that by slashes.
You can use a map() and a join() to get that structure. - this is hte same solution as Puwka's = but without the template literal.
var data = [
{am: 1, ct: "", pc: "1000000025"},
{am: 2, ct: "", pc: "1000000013"}
];
let newArr = data.map(item => "[" + item.pc +"]");
console.log(newArr.join("/")); // gives [1000000025]/[1000000013]
You can always use classic for in loop
let arr = [{PC:'1000'},{PC:'10000'}]
let arrOut = [];
for(let i = 0; i < arr.length; i++) {
arrOut.push('[' + arr[i].PC + ']');
}
now the arrOut is equal ["[1000]", "[10000]"] what we need is to convert it to a string and add '/' between items.
let str = arrOut.join('/');
console.log(str) // "[1000]/[10000]"
So you need a string in the format of: xxxx/yyyyy from a complex object array.
const basedata = [...];
const result = basedata.map( item => `[${item.PC}]` ).join('/')
so i will explain it now. The map function will return a new array with 1 entry per item. I state that I want PC, but i added some flavor using ticks to inject it inbetween some brackets. At this point it looks like: ["[1000000025]","[100000013]"] and then join will join the arrays on a slash, so it will turn into an array.
"[100000025]/[100000013]"
Now, this will expand based on the items in your basedata. So if you have 3 items in your basedata array, it would return:
"[10000000025]/[100000013]/[10000888]"
First if you want to divide the result then it will be better to change it into number and then just do the division.
Example
Number.parseInt("100000025")/Number.parseInt("100000013")
If you want to display it then better to use string interpolation
surround it with back tick
[${[0].PC}]/[${[1].PC}]
Hope this is what are you looking for

Use float as array key

I want to use an array to look up a value given a key. AFAIK, it should be possible when converting the float to a string, like the second example below: (jsfiddle)
arr = [];
arr[1.3] = "One point three";
console.log(arr.length);
arr = [];
arr["1.3"] = "One point three";
console.log(arr.length);
But both result in a zero-length array. What am I doing wrong? I.e. how can I look up an object/string/whatever given a float value?
It would be awesome to have a reference guide on common operations when using having to look up values, such as:
get an element, given a float key
get total number of elements
test if float key exists
put new float key / value pair
and maybe others, such as loop through all keys/values
Array's index must be an integer for adding it as an array item. If you will pass to the [] not an integer, it will be added as a property.
arr = [];
arr[1.3] = "One point three";
console.log(arr.length);
console.log(arr.hasOwnProperty('1.3'));
console.log(Object.keys(arr).length);
I could be wrong, but it seems you are trying to create a dict. I would just use an object like others have suggested.
var arr = {
1.2: 'One Point Three'
}
arr[1.2] or arr["1.2"] // One Point Three
or you can use es6 Map
var arr = new Map()
arr.set(1.3, "One Point Three")
arr.get(1.3) // One Point Three
arr.size // 1
An array takes an integer value as index.
You should be using an Object for this kind of mapping.
var arr = {};
arr[1.3] = "One point three";
console.log(Object.keys(arr).length);
Suren's answer was the first, and gave me what I needed to establish a reference of operations:
Insert an item:
var x = 1.3;
// Not actually an array! arr.length will be undefined. Although
// an array could still be used, it seems
var arr = {};
arr[x] = "One point three";
Count items:
Object.keys(arr).length
Test if key exists:
arr.hasOwnProperty(x)
Get an element:
arr[x]
Loop through key/value pairs
for (key in arr)
{
var value = arr[key];
}
Interesting quirks
+1 to James Emanon for several points: Firstly, showing that a string is not necessary for lookup:
arr[1.3] // works
Secondly, the array can be defined as an object like so:
arr = {
1.3: "One point three"
};
Thirdly, ES6 provides a Map object. Will be useful.

all possible combinations in javascript - why pop()?

I'm trying to understand this function that I came across online that returns all possible combinations of a string -- why exactly is the pop() call needed with nextLetter.pop? I tried debugging this in the console but it's not clear what the pop does exactly.
result with nextLetter.pop() ---> [ 'bac', 'bca', 'cba', 'cab', 'acb', 'abc' ]
result without nextLetter.pop() --> [ 'bac',
'bacca',
'baccacba',
'baccacbaab',
'baccacbaabacb',
'baccacbaabacbbc' ]
function stringPermutations(str) {
var permutations = [];
var nextLetter = [];
var chars = str.split('');
permutateInner(chars);
function permutateInner(chars) {
if (chars.length === 0) {
permutations.push(nextLetter.join(''));
}
for (var i = 0; i < chars.length; i++) {
chars.push(chars.shift());
nextLetter.push(chars[0]);
permutateInner(chars.slice(1));
//what is this doing?
nextLetter.pop();
}
}
return permutations;
}
console.log(stringPermutations('abc'));
permutateInner(chars.slice(1)); does recursion on array subset [1..n]. It is included to have permutation also for each subarray of current array.
e.g. when current first letter is b, recursion includes permutations ac and ca. when current first letter is a, recursion includes permutations cb and bc.
It is crucial to have it there, otherwise you would get only result [ 'abc', 'bca', 'cba' ]
Starting at the top, it's clear that nextLetter is an Array -- so the first place I'd look would be the docs on MDN.
As the documentation says, the .pop() method removes the last element from the Array and returns it -- in your sample code the return value isn't being used, so clearly what's useful is the side effect of removing the last element.

Javascript : How do I call the array index of the string?

Hello I have a problem when you change the string in order to invoke an array in javascript, please help me,
I have had a array:
var fruit=['Apple','Banana','Orange'];
and I have data string from mysql:
example: var string = '0,2';
How to display an array of fruit which corresponds to the var string?
(Thanks for the help)
You have to split() the string to get an array of indexes instead of a string of indexes :
var indexes = '0,2'.split(','); //use the ',' char to split the string
Now, you have to pick fruits values corresponding to each index in the new indexes array create just before.
var res = []; //The new Array to contains new fruits
indexes.forEach(function(index) { //loop over fruit indexes we want
res.push(fruit[index]); //Add the juicy fruit :)
});
And you got the new array (res) with the juicy fruits :)
JSFiddle
EDIT:
Or, a shorter/nicer solution (thanks to Xotic750)
(the second argument of the map function specify the context (this))
var ids = '0,2';
var fruits = ['Apple','Banana','Orange'];
fruits = ids.split(',').map(function(index) {
return this[index];
}, fruits);
I don't know if it will work or not, but this is what I could think of:
var x = [];
for (var i = 0; i>=string.length; i+=2) {
x.push(fruit[string[i]]);
}
But use only even numbers as a comma is also present in the string.
You will need to split the string into an array by using the Split() method:
var myArray = string.split(",");
Then you can loop over the array and use its values as indexes in the fruit array. For example, the first fruit will be:
fruit[myArray[0]];

Categories

Resources