javascript object, concatenate duplicate keys while keeping multiple values - javascript

I have javascript objects that follow this pattern. Keys are to the left of the = sign, values to the right. The keys that are duplicates need to be concatenated to one key while keeping all the values.
var arrUnique = ['arTitle=randomword','arTitle=random','beTitle=rand1','bnTitle=whatever','caTitle=mango','caTitle=mangoes']
Becomes this string:
arTitle = ['randomword','random' ], beTitle = ['rand1'], bnTitle = ['whatever'], caTitle = ['mango','mangoes']
Here is where I am at so far. Create an object with all the keys using regex. Then create a regex construction which loops through each object in keys and pushes to x only when it matches more then 1.
var keys = (/\w{2}Title=/gi);
var x = [];
for (i = 0; i < arrUniqueCount; i++){
var regexp = new RegExp(keys[i], "gi");
var str2 = arrUniqueString.match(regexp).length;
if (str2 > 1){
x.push(regexp[i])}
}
alert("repeats: " + x);
Next I was thinking of using regex to replace and match etc to finally get my outcome. I am finding this stage difficult. Would anybody mind sharing a better way?

I would go the route of just sliptting at the '=' sign then adding them to an object based on the key at index position 0 of that split.
var arrUnique = ['arTitle=randomword', 'arTitle=random', 'beTitle=rand1', 'bnTitle=whatever', 'caTitle=mango', 'caTitle=mangoes'];
//object to collect the final result in
var result = {};
//go through each item and split on the equal
//this will create an array or arrays that contain your key/value
arrUnique.map(function(x) {
return x.split("=");
}).forEach(function(item) {
//if the key doesn;t yet exist in the object declare it as an empty array
if (!result[item[0]]) {
result[item[0]] = [];
}
//push the value onto this key
result[item[0]].push(item[1]);
});
console.log(result);

Related

creating new values by index in JS looping/arrays

I have an array of values:
let myArray = [ 'Ifmanwas',
'meanttos',
'tayonthe',
'groundgo',
'dwouldha',
'vegivenu',
'sroots' ]
I want to print out a new value for each item in the array so that the first item is a collection of all the characters at the zero index, the second is a collection of all the characters at the 1 index position, ect...
So for instance, the output of the first array would be "Imtgdvs" (all the letters at ("0"), the second would be "fearwer" (all the letters at index "1") ect...
I am very lost on how to do this and have tried multiple different ways, any help is appreciated.
For this simple attempt I have created an array of all the letters for the first instance:
function convertToCode(box) {
let arr = [];
for (i = 0; i < box.length; i++) {
let counter = i;
let index = box[counter];
let letter = index.charAt(0);
arr.push(letter);
}
console.log(arr);
}
convertToCode(myArray)
Thanks
The main issue in your example is this: index.charAt(0);. This will always get the first character, whereas you need a nested loop.
You could use Array.map() in combination with Array.reduce(), like so:
let myArray = ['Ifmanwas','meanttos','tayonthe','groundgo','dwouldha','vegivenu','sroots'];
const result = Array.from(myArray[0]) //Create an array as long as our first string
.map((l,idx) => //Update each item in that array...
myArray.reduce((out,str) => str[idx] ? out+str[idx] : out, "") //to be a combination of all letters at index [idx] from original array
);
console.log(result);
Note that this uses the first string in the array to decide how many strings to make, as opposed to the longest string.

Javascript array not creating an array

I have an array with items and I want to group them according the first letter but when I push the item to the array it shows empty "Array[0]" while there are clearly items in it.
Apparently I'm doing something wrong but i have no idea what.
var group = [];
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
Arrays are designed to hold an ordered set of data represented by property names which are integers.
You are assigning property names which are letters.
Arrays are not designed to hold that kind of data and console.log doesn't display those properties for arrays.
Don't use an array. Use an object. Objects are designed to hold unordered data with arbitrary property names. If order matters, then you might want to use a Map instead.
You are looking to create an object instead of an array. Change the [] to {}
An Array expects an int as index, the object can take a string
var group = {}; // Object instead of Array
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
alphabetArray.forEach(function(letter) {
group[letter] = group[letter] || [];
group[letter].push({
key: letter,
letter
});
});
console.log(group);
I guess you want to transform each letter to structure. I f so, you need Array.map:
var alphabetArray = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'.split('');
var group = alphabetArray.map(function(letter) {
return {
[letter]: letter
};
});
console.log(group);

Adding Characters to the Begining of an Array that form words

When looking at set of characters I am trying to put each letter into a specifc order in an array. For Example: Given the Strings "cat" and "dog" I would want an array that contains [d,o,g,c,a,t], cat at the end of the array because it was read first.
Currently I have tried this:
However, when I try the code below assuming the strings are "cat" and "dog".
I get an array containing: [c,a,t,d,o,g]. Instead of push I have also tried .unshift but the array now reads: [g,o,d,t,a,c].
var chars = /^[a-z]$/;
var string = [];
function makeword(){
if(currentChar.match(chars)){
string.push(currentChar);
currentChar = getNextChar(); //Gets next Character in the String
makeword();
}
}
Is something like this possible in Javascript?
If I understood you correctly, you want to provide a list of strings, then have them show up in an array in reverse order, with each letter as an element of the array. The following function will do just that:
function makeWords() {
var arr = [];
for(var i = arguments.length - 1; i >=0; i--) {
arr.push(arguments[i]);
}
return arr.join('').split('');
}
so running makeWords('cat', 'dog') will result in ['d','o','g','c','a','t'].
It's a relatively simple code when a functional approach is used. The rest and spread operators are very handy both to collect the function arguments and to spread the characters of a word into an array.
var characterify = (...c) => c.reduceRight((a,b) => a.concat([...b]) ,[]);
document.write("<pre>" + JSON.stringify(characterify("cat","dog")) + "</pre>");

Value set inside if doesn t carry on [duplicate]

How can I convert a JavaScript associative array into JSON?
I have tried the following:
var AssocArray = new Array();
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]);
// result: "a = The letter A"
JSON.stringify(AssocArray);
// result: "[]"
Arrays should only have entries with numerical keys (arrays are also objects but you really should not mix these).
If you convert an array to JSON, the process will only take numerical properties into account. Other properties are simply ignored and that's why you get an empty array as result. Maybe this more obvious if you look at the length of the array:
> AssocArray.length
0
What is often referred to as "associative array" is actually just an object in JS:
var AssocArray = {}; // <- initialize an object, not an array
AssocArray["a"] = "The letter A"
console.log("a = " + AssocArray["a"]); // "a = The letter A"
JSON.stringify(AssocArray); // "{"a":"The letter A"}"
Properties of objects can be accessed via array notation or dot notation (if the key is not a reserved keyword). Thus AssocArray.a is the same as AssocArray['a'].
There are no associative arrays in JavaScript. However, there are objects with named properties, so just don't initialise your "array" with new Array, then it becomes a generic object.
Agreed that it is probably best practice to keep Objects as objects and Arrays as arrays. However, if you have an Object with named properties that you are treating as an array, here is how it can be done:
let tempArr = [];
Object.keys(objectArr).forEach( (element) => {
tempArr.push(objectArr[element]);
});
let json = JSON.stringify(tempArr);
I posted a fix for this here
You can use this function to modify JSON.stringify to encode arrays, just post it near the beginning of your script (check the link above for more detail):
// Upgrade for JSON.stringify, updated to allow arrays
(function(){
// Convert array to object
var convArrToObj = function(array){
var thisEleObj = new Object();
if(typeof array == "object"){
for(var i in array){
var thisEle = convArrToObj(array[i]);
thisEleObj[i] = thisEle;
}
}else {
thisEleObj = array;
}
return thisEleObj;
};
var oldJSONStringify = JSON.stringify;
JSON.stringify = function(input){
if(oldJSONStringify(input) == '[]')
return oldJSONStringify(convArrToObj(input));
else
return oldJSONStringify(input);
};
})();
You might want to push the object into the array
enter code here
var AssocArray = new Array();
AssocArray.push( "The letter A");
console.log("a = " + AssocArray[0]);
// result: "a = The letter A"
console.log( AssocArray[0]);
JSON.stringify(AssocArray);

Javascript check every char in a string and return array element on corresponding position

Got a string that is a series of 0 or 1 bit and an array of values, if in the string are characters that are set to 1, I need to return the corresponding value from the array.
example: mystring = "0101"; myarray =["A","B","C","D"]; then result = "B,D"
how can I get this result?
for(var i=0;i<mystring.length;i++){
if(mystring[i] != 0)
{
result = myarray[i];
}
}
Your code seems to work just fine, so you can just add another array and push the values on to that:
var result = [];
for (var i = 0 ...
result.push(myarray[i]);
http://jsfiddle.net/ExplosionPIlls/syA2c/
A more clever way to do this would be to apply a filter to myarray that checks the corresponding mystring index.
myarray.filter(function (_, idx) {
return +mystring[idx];
})
http://jsfiddle.net/ExplosionPIlls/syA2c/1/
Iterate through the characters in the binary string, if you encounter a 1, add the value at the corresponding index in the array to a temporary array. Join the temporary array by commas to get the output string.
I am not really sure if this is what you are looking for, but this returns the array of matches.
var result = [];
for(var i=0;i<mystring.length;i++){
if(parseInt(mystring[i]) !== 0 ) {
result.push(myarray[i]);
}
}
return result;
result = new Array();
for(var i=0;i

Categories