Processing the data into a desired format in javaScript - javascript

I am new to JavaScript and want to process the following array -
var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
into the following format -
a = {
"John": [100, 50],
"Mark": [120, 130]
}
But have been unable to do so. Any help will be very much appreciated.
Edit - Any other format ideas where the marks of a particular student can be grouped together are also welcome.

Here is one way to achieve what you described:
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
function convertToSpecialObject(input) {
//setup the output as an empty object
const output = {};
// iterate through input array one element at a time
input.forEach(e => {
// split the current element by dividing it into part[0] before the dash
// and part[1] after the dash sign
const parts = e.split(/-/);
// now check the output object if it already contains a key for the part before the dash
if(!output[parts[0]]) {
// in this case, we don't have a key for it previously
// so lets set it up as a key with an empty array
output[parts[0]] = [];
}
// we must have already created a key or there is a key in existence
// so let's just push the part after the dash to the current key
output[parts[0]].push(Number(parts[1]));
});
// work done
return output;
}
const b = convertToSpecialObject(a);
console.log(b);

you can achieve this by using reduce and split method
var a=[
"John-100",
"Mark-120",
"John-50",
"Mark-130"
]
const b = a.reduce((acc, val) => {
const _split = val.split('-');
const name = _split[0]
if(acc && acc[name]) {
acc[name].push(+_split[1])
} else {
acc[name] = [+_split[1]]
}
return acc;
}, {});
console.log(b)

You can achieve it in a very simple way by just using a Array.forEach() method along with the String.split().
Live Demo :
var a = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];
const obj = {};
a.forEach(element => {
if (!obj[element.split('-')[0]]) {
obj[element.split('-')[0]] = [];
}
obj[element.split('-')[0]].push(element.split('-')[1])
});
console.log(obj);

With Simple Approach
const input = [
"John-100",
"Mark-120",
"John-50",
"Mark-130"
];
const getCustomObject = (arr) => {
const obj = {};
for (let i = 0; i < arr.length; i++) {
const split = arr[i].split('-'); //spliting with '-'
if (obj[split[0]]) {
//push to existing array
obj[split[0]].push(split[1]);
} else {
obj[split[0]] = []; //initilize array if no member
obj[split[0]].push(split[1]);
}
};
return obj;
}
console.log(getCustomObject(input));
Now numbers are not numerical values, It can be achieved with parseInt or parseFloat

As I suggested, string split, and array reduce - add in an array map and it's a single line of code
let a=["John-100","Mark-120","John-50","Mark-130"];
a=a.map(v=>v.split('-')).reduce((r,[n,m])=>({...r,[n]:[...r[n]||[],+m]}),{});
console.log(JSON.stringify(a));
The only answer with the correct result ... an array of NUMBERS

Related

Replace instances of an array in a string with another array

I'm working on a JS applet that requires replacement of array entries in a given string with entires from another array. This is my code as it now stands:
const string = "Lion, Unicorn, Unicorn";
const array1 = ["Lion", "Unicorn"];
const array2 = ["Fox", "Hound"];
const string2 = string.replaceAll(array1[0],array2[0]) //returns "Fox, Unicorn, Unicorn"
My desired output is :
Fox, Hound, Hound.
Specifically, I'd like to turn the contents of string2 into a function that repeats for every item in an array, but have no idea where to start.
Thanks!
Do you mean something like this?
I hope I understood the question well.
You can write a recursive function:
let string = "Lion, Unicorn, Unicorn";
let array1 = ["Lion", "Unicorn"];
let array2 = ["Fox", "Hound"];
function myCustomReplace(str, a1, a2) {
let wordToReplace=a1.shift(); // a1[0] - if array change matters
let replacementWord=a2.shift(); // a2[0] - if array change matters
if (!wordToReplace || !replacementWord) return str;
str=str.replaceAll(wordToReplace, replacementWord );
return myCustomReplace(str,a1,a2); // rturn myCustomReplace(str,a1.slice(1),a2.slice(1)) - if array change matters
}
console.log(
myCustomReplace(string,array1,array2)
)
It's sometimes worthwhile to first transform the inputs into a shape that is easier to work on. For this problem, the input sentence is better thought of as an array of words, and the two arrays used for replacement are better represented as a single object mapping input words to output words...
let string = "Lion, Unicorn, Unicorn";
let array1 = ["Lion", "Unicorn"];
let array2 = ["Fox", "Hound"];
// transform the inputs
let input = string.split(", ");
let translator = array1.reduce((acc, key, i) => {
acc[key] = array2[i];
return acc;
}, {});
// now input is ['Lion', 'Unicorn', ...]
// and transator is { 'Lion' : 'Fox', ... }
// now the problem is just a two-liner, mapping the input over the translator
let output = input.map(e => translator[e] || e)
console.log(output.join(", "))
If we use split(', ') to convert the string to an array of single words, we can use map() to replace them by searching for a pair with indexOf():
Please see comments in the code. A one-liner can be found at the end.
const string = "Lion, Unicorn, Unicorn";
const array1 = ["Lion", "Unicorn"];
const array2 = ["Fox", "Hound"];
// Split on ', '
let splitted = string.split(', ');
// Map
let result = splitted.map(w => {
// Get position in array1
const i = array1.indexOf(w);
// If we've found something
if (i !== -1) {
// Return replacement
return array2[i];
} else {
// Return original
return w;
}
});
// Create string
result = result.join(', ');
// Show
console.log(result);
// Or, as a one-liner
let result2 = string.split(', ').map(w => (array1.indexOf(w) !== -1) ? array2[array1.indexOf(w)] : w).join(', ');
console.log(result2);

texts in array converts to objects

I am using node to convert an array to object, I have an array looks like this
[
'items[0].book=Book1',
'items[0].color=Red',
'items[0].bookCode=#1',
'items[1].book=Book2',
'items[1].color=Yellow',
'items[1].bookCode=#2',
'items[2].book=Book3',
'items[2].color=Blue',
'items[2].bookCode=#3',
...
]
I am trying to convert it to be objets in one array
items:[
{
book: "Book1",
color: "Red",
bookCode: "#1"
},
{
book: "Book2",
color: "Yellow",
bookCode: "#2"
},
...
]
I found it is easy to conver it uses a 3rd party lib like setKeypath/set,
const obj = {};
const arr = [items......(like above)]
arr.forEach((val => {
if (val.startsWith('items[')) {
const splitWord = item.split('=');
setKeypath(obj, splitWord[0], splitWord[1]);
}
});
I am seeking a way if it can be done the same output with es6, so I don't really need a library. Thanks
const items = [
"items[0].book=Book1",
"items[0].color=Red",
"items[0].bookCode=#1",
"items[1].book=Book2",
"items[1].color=Yellow",
"items[1].bookCode=#2",
"items[2].book=Book3",
"items[2].color=Blue",
"items[2].bookCode=#3"
];
let res = [];
let currId = "";
let currItem = null;
for (let i = 0; i < items.length; i++) {
let parts = items[i].split(".");
if (currId!==parts[0] && currItem) { //new item
res.push(currItem)
currId = parts[0];
}
if (!currItem)
currItem = {};
let keyValue = parts[1].split("=");
currItem[keyValue[0]] = keyValue[1]
}
console.log({items: res})
You may first find all values by regex, and insert the attribute to each corresponding element one by one. This approach works for whatever ordering the array is, and whatever attributes there are, as long as each element follow the same pattern.
let items = [
"items[1].bookCode=#2",
"items[0].book=Book1",
"items[0].bookCode=#1",
"items[1].book=Book2",
"items[2].bookCode=#3",
"items[1].color=Yellow",
"items[2].book=Book3",
"items[2].color=Blue",
"items[0].color=Red",
"items[4].test=test!"
];
let indexPattern = /\[(\d*)\]/;
let attrPattern = /\.(.*)=/;
let valuePattern = /=(.*)/;
let obj = Object.values(
items.reduce((obj, element) => {
let index = element.match(indexPattern)[1];
let attr = element.match(attrPattern)[1];
let value = element.match(valuePattern)[1];
if (!obj.hasOwnProperty(index)) obj[index] = {};
obj[index][attr] = value;
return obj;
}, {})
);
console.log(obj);
[
'items[0].book=Book1',
'items[0].color=Red',
'items[0].bookCode=#1',
'items[1].book=Book2',
'items[1].color=Yellow',
'items[1].bookCode=#2',
'items[2].book=Book3',
'items[2].color=Blue',
'items[2].bookCode=#3',
].reduce((acc, str) => {
const index = Number(str.slice(str.indexOf('[') + 1, str.indexOf(']')));
if (!acc[index]) {
acc[index] = {};
}
const entry = [str.slice(str.indexOf('.') + 1, str.indexOf('=')), str.slice(str.indexOf('=') + 1)];
acc[index][entry[0]] = entry[1];
return acc;
}, []);
Here I pick apart the string you're given based on the consistent format, grab the index, key, and value, and then just use Array#reduce to do the work of putting the array together.
Documentation:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce
I think a smattering of regex would do the trick:
const ar = [
'items[0].book=Book1',
'items[0].color=Red',
'items[0].bookCode=#1',
'items[1].book=Book2',
'items[1].color=Yellow',
'items[1].bookCode=#2',
'items[2].book=Book3',
'items[2].color=Blue',
'items[2].bookCode=#3'
]
const result = [];
ar.forEach(item => {
const index = parseInt(item.match(/\[([0-9]+)\]/)[1]);
const params = item.split(".")[1].split("=");
if(!result[index])
result[index] = {}
result[index][params[0]] = params[1];
})
console.log(result)
Note that item.match(/\[([0-9]+)\]/) matches the number inside your brackets. match returns an array where 1 is the index of the actual value between the brackets.

Is there any way to search for something below a certain value inside a couple arrays?

I have the following JSON:
{
"hominis": [20000, "asd"],
"omint": [30000, "asd"]
}
and I would like to make a function that returns all array names (hominis, omint) whose arr[0] value is under my input value
e.g:
if (myInput <= arr[0]) {
return arrName
}
I would like to go through my arrays (hominis, omint) and return their names if the condition is matched. I believe it has something to do with for loops, but I couldn't do it.
I've started JS two weeks ago so I'm a newbie.
Thank you
You can iterate over the keys of an object like following snippet,
var a = {
"hominis": [20000, "asd"],
"omint": [30000, "asd"]
};
var minValue = 25000;
var keys = Object.keys(a); // Returns all keys in the object
for (let key of keys) { // Loop over all the keys
if (a[key][0] > minValue) { // Check if value at key matches your condition
console.log(key); // return/add to your new array/ or whatever to the matching key
}
}
You did not say how to show your output. I am assuming it will be array of names.
let data = {
hominis: [20000, "asd"],
omint: [30000, "asd"],
};
myInput = 20001;
let x = Object.entries(data).reduce((p, [x, y]) => {
if (myInput <= y[0]) p.push(x);
return p;
}, []);
console.log(x);
You can use "for in obj".
var obj1 = {
"hominis": [20000, "asd"],
"omint": [30000, "asd"]
}
function findMinorThan(obj, limit) {
let res = []
for (const k in obj) {
if (obj[k][0] < limit) {
res.push(k)
}
}
return res
}
console.log(findMinorThan(obj1, 25000));

How to transform a js array to make it by day

const arr = [
{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}
];
I have an array as you can see in the snippet. My issue is I need to check something per day:
For each day when A value > 60 or when B value > 6 then do something.
Else when A value <= 60 and when B value <= 6 then do something else.
And I don't know how to do this check with the current array structure as each step in the loop is a different day. I want to compare all values for one day at the same time.
Is it possible to transform the array to look like this? Then I will be able to compare day per day...
const arr = [
{"datetime":"2018/8/5","valueA":85,"valueB":undefined},
{"datetime":"2018/8/10","valueB":7,"valueA":73}
];
Thank you!
You can make a the date groups by reducing into an object. Then just set the appropriate value in that object. In the end your array will be in the Object.keys() of the grouped object.
[As you might surmise from the comments, the order of the final array is not guaranteed because object keys and values are not guaranteed. If your original data is ordered by date, you should say so in the question because there will be more efficient ways to do this if the order is guaranteed].
const arr = [{"datetime":"2018/8/5","value":85,"type":"A"},{"datetime":"2018/8/10","value":7,"type":"B"},{"datetime":"2018/8/10","value":73,"type":"A"}];
let groups = arr.reduce((obj, {datetime, value, type}) => {
if (!obj[datetime]) obj[datetime] = {datetime, valueA:undefined, valueB:undefined}
let currentKey = type == 'A' ? "valueA" : "valueB"
obj[datetime][currentKey] = value
return obj
},{})
let newArr = Object.values(groups)
console.log(newArr)
This will transform the array as OP asked for, and will respect the order.
const arr = [{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}];
var daysArr = []
arr.map(function(day){
var keyName = 'value'+day.type
var found = false
var dayObj = {}
for (var i=0; i < daysArr.length; i++) {
if (daysArr[i].datetime === day.datetime) {
daysArr[i][keyName] = day.value;
found = true
break
}
}
if (!found) {
dayObj = {"datetime":day.datetime,valueA:undefined,valueB:undefined}
dayObj[keyName] = day.value
daysArr.push(dayObj)
}
})
console.log(daysArr);
One solution could be using reduce(). Note that if a key is not defined will return undefined (this is exemplified on the second log to the console), so I consider redundant to define, for example "value-B": undefined, unless you want to assign to it another default value.
Warning: As discussed on the comments, you should note that the order of the final result, may not be preserved.
const arr = [
{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}
];
let res = arr.reduce((acc, {datetime, value, type: type}) =>
{
acc[datetime] = acc[datetime] || {};
Object.assign(acc[datetime], {datetime, [`value-${type}`]: value});
return acc;
}, {});
console.log(Object.values(res));
console.log(Object.values(res)[0]["value-B"]);
You could do this:
<html>
<head>
<meta charset="UTF-8"></meta>
<script type="text/javascript">
const arr = [{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}];
var new_arr = group_items(arr)
console.log(new_arr)
function group_items(arr)
{
var ret_arr = []
for(var x=0;x<arr.length;x++)
{
var cur_date = arr[x].datetime
var pos = lookup_date(cur_date, ret_arr)
var obj = {}
obj.datetime = cur_date
if(pos != false)
{
//add to existing item
if(arr[x].type == 'A')
{
ret_arr[pos].valueA = arr[x].value
}
else if(arr[x].type == 'B')
{
ret_arr[pos].valueB = arr[x].value
}
}
else{
if(arr[x].type == 'A')
{
obj.valueA = arr[x].value
}
else if(arr[x].type == 'B')
{
obj.valueB = arr[x].value
}
ret_arr.push(obj)
}
}
return ret_arr
}
function lookup_date(date, arr)
{
/*
returns the position in arr of date
*/
var retval = false
for(var x=0;x<arr.length;x++)
{
if(arr[x].datetime == date)
{
retval = x
break
}
}
return retval
}
</script>
</head>
<body>
</body>
If you don't need the final array to include the datetimes in the same order as the original, then you can just make an object that maps datetimes to the corresponding values and then use Object.values to get the final array. This approach does not guarantee order, since objects are unordered data structures:
const arr = [
{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}
];
const values_by_date = { };
arr.forEach( ({ datetime, type, value }) =>
values_by_date[ datetime ] = {
datetime/*, valueA: undefined, valueB: undefined*/,
...values_by_date[ datetime ], [`value${type}`]: value
}
);
const result = Object.values( values_by_date );
console.log( result );
If you need the final array to include the datetimes in the same order as the original array and the original array is already sorted by datetime, you can do it in a single pass like this:
const arr = [
{"datetime":"2018/8/5","value":85,"type":"A"},
{"datetime":"2018/8/10","value":7,"type":"B"},
{"datetime":"2018/8/10","value":73,"type":"A"}
];
const result = arr.reduce( ({ result, datetime: prev }, { datetime, type, value }) => {
if ( datetime !== prev )
result.push( { datetime/*, valueA: undefined, valueB: undefined*/ } );
Object.assign( result[ result.length - 1 ], { [`value${type}`]: value } );
return { result, datetime };
}, { result: [] } ).result;
console.log( result );
Note: In either snippet you can uncomment /*, valueA: undefined, valueB: undefined*/ if you want the resulting objects to include properties for the missing values.

create a grouped array using two different arrays

I have below two arrays:
array1 = [{
"type":"test",
"name":"name1"},
{
"type":"dev",
"name":"name2"}]
array2=[{
"type":"test",
"name":"name3"},
{
"type":"dev",
"name":"name4"},
{
"type":"prod",
"name":"name5"}]
I want to group two arrays with "type" and create a new array something like this:
finalArray=[{
"type":"test",
"info":[{
"type":"test",
"name":"name1"}],
[{
"type":"test",
"name":"name3"
}]},
{
"type":"dev",
"info":[{
"type":"dev",
"name":"name2"}],
[{
"type":"dev",
"name":"name4"}]},
{
"type":"prod",
"info":[],
[{
"type":"prod",
"name":"name5"}]
}]
Is there anyway that I can achieve this using javascript, angularjs2, lodash, jquery. I am able to group and create new object as mentioned in using lodash .groupBy. how to add your own keys for grouped output?
But only thing is always I want to push the data from second array in index=1 of "info" and first one to index=0. If any of the array does not have a "type" then the "info" array should have empty/null values.
use _.mapValues to iterate object values with key accessing
var res = _.chain(array1)
.concat(array2)
.groupBy('type')
.mapValues(function(val, key) {
return {
type: key,
info: val
};
})
.values()
.value();
It's possible to achieve the result you want in javascript, or using helper like lodash.
The last part of your question is hard to understand. If an array doesn't have "type", how would you group them. Please provide clearer explanation or modify your expected input and output.
[Updated]
Thanks for your explanation. This is the solution using plain javascript.
// get uniques type from two arrays
const uniqueTypes = new Set(array1
.concat(array2)
.map(x => x.type));
// loop the types, find item in both array
// group it
let result = Array.from(uniqueTypes).reduce((acc, curr) => {
const item1 = array1.find(x => x.type === curr);
const item2 = array2.find(x => x.type === curr);
const info1 = item1 ? [item1] : [];
const info2 = item2 ? [item2] : [];
acc = acc.concat({ type: curr, info: [info1, info2] });
return acc;
}, []);
console.log(result);
jsbin here: https://jsbin.com/mobezogaso/edit?js,console
Here's a working solution :). Hope it helps!
var array1 = [
{
"type":"test",
"name":"name1"
},
{
"type":"dev",
"name":"name2"
}
]
var array2 = [
{
"type":"test",
"name":"name3"
},
{
"type":"dev",
"name":"name4"
},
{
"type":"prod",
"name":"name5"
}
]
var newArray = array1.concat(array2);
var arr1 = [];
var arr2 = [];
var arr3 = [];
var arrTypes = [];
var finalArray = [];
var someArray = [];
for(var i in newArray)
{
if (arrTypes.indexOf(newArray[i].type) === -1){
arrTypes.push(newArray[i].type);
}
if(newArray[i].type === "test"){
arr1.push(newArray[i]);
}
else if(newArray[i].type === "dev"){
arr2.push(newArray[i]);
}
else if(newArray[i].type === "prod"){
arr3.push(newArray[i]);
}
}
someArray.push(arr1);
someArray.push(arr2);
someArray.push(arr3);
for(var j = 0; j < someArray.length; j++){
finalArray.push({
"type": arrTypes[j],
"info": someArray[j]
});
}
console.log(finalArray);
And a short (unreadable?) ES6 solution:
Concat the arrays
Reduce the array into a Map object, with the type as the key
Get the entries iterator - key (type) - value (array of objects)
Use spread to convert the entry iterator to an array
Array#Map the array of entries to the type/info objects
const array1 = [{"type":"test","name":"name1"},{"type":"dev","name":"name2"}];
const array2=[{"type":"test","name":"name3"},{"type":"dev","name":"name4"},{"type":"prod","name":"name5"}];
const result = [...array1.concat(array2).reduce((r, o) => {
r.has(o.type) ? r.get(o.type).push(o) : r.set(o.type, [o]);
return r;
}, new Map).entries()]
.map(([type, info]) => ({
type, info
}));
console.log(result);

Categories