How to make two arrays from this json data? - javascript

My data is animalCount: {Tiger: 3, Leopard: 6, Rat: 1}
So I need to have 1st array
name :['Tiger', 'Leopard', 'Rat']
2nd array
count: [3, 6, 1]
Is it possible to obtain the same?

Sure, just use:
const names = Object.keys(animalCount);
const values = Object.values(animalCount);

As others have mentioned, you can use:
var name = Object.keys(animalCount);
var count = Object.values(animalCount);
If you, for some reason, needed to manipulate or change them while creating these arrays, you could also use a for i in animalCount loop, like so:
var animalCount = {Tiger: 3, Leopard: 6, Rat: 1};
var array1 = [];
var array2 = [];
for(i in animalCount){
if(animalCount.hasOwnProperty(i)){
array1.push(i);
array2.push(animalCount[i]);
}
}
console.log(array1);
console.log(array2);

How about
var name = [];
var count = [];
for(var prop in animalCount){
name.push(prop);
count.push(animalCount[prop]);
}
This way we're sure the order is preserved.

JS supports this natively.
var name = Object.keys(animalCount);
var count = Object.values(animalCount);
See:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys for Object.keys and
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/values for Object.values

You could take a single loop and reduce the entries of the object by iterating the key/value array for pushing the items.
var animalCount = { Tiger: 3, Leopard: 6, Rat: 1 },
names = [],
count = [],
result = Object
.entries(animalCount)
.reduce((r, a) => (a.forEach((v, i) => r[i].push(v)), r), [names, count]);
console.log(names);
console.log(count);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Related

How to declare an array of values within an array of objects using JS?

I want to create an array containing objects that have a key data which is an array of values. I am trying to push values into data but it's not working for me.
My expected result looks like this:
array = [
{ data:[3,2,5] },
{ data:[5,2,1] }
]
So I want to fill the data arrays. To do this, I have tried populating the arrays with a for loop:
var array = [];
for(i=0;i<2;i++){
for(j=0;j<3;j++){
array[i]["data"][j].push(2);
}
}
But this is not working for me.
You can't do this: array[i]["data"][j].push(2) without first initializing array[i].
In your case there's no need to initialize it with an empty array, instead you can simply assign the whole object to each [i]
What you are trying to achieve is an array of objects where each object is of the form {'data': []}
So assume you have your input coming from an array:
const initialData = [[3, 2, 5], [5, 2, 1]];
To get that data in the form you want it, you would do:
const initialData = [[3, 2, 5], [5, 2, 1]];
var array = [];
for(i=0;i < initialData.length; i++){
array[i] = {'data':initialData[i]};
}
console.log(array)
And here is a neater approach using some of Array.prototype's methods which I recommend checking out:
const initialData = [[3, 2, 5], [5, 2, 1]];
const array = initialData.map(elem => {
return {
'data': elem
};
})
console.log(array)
And if you want neaterer you can go with mplungjan's comment
You can initialize the array with: const array = [...Array(2)].map(() => ({ data: [] }));
Then you'll be able to access it with:
for(i=0; i<2; i++){
for(j=0;j<3;j++){
array[i].data[j] = 2;
}
}
Take a look at these changes, which modify your existing code. For an improved method, see the bottom
Your Code
var array = [];
for(i=0;i<2;i++){
array.push({data:[]}) // create your object
for(j=0;j<3;j++){
array[i]["data"].push(2); // you don't need '[j]' because the result of 'data' key is an array, so just push onto it
}
}
console.log(array)
Alternative Method
let arr = [...new Array(2)].map(el=>({ data: new Array(3).fill(2) }));
console.log(arr)
You could do something like this:
let items = 2
let arr = Array.from({ length: items }, (item) => item = { data: [] })
for (let i = 0; i < items; i++) {
for (let j = 0; j < 3; j++) {
let val = 2 // replace value here
arr[i].data.push(val)
}
}
console.log(arr);

How do you merge the item values from 2 separate arrays in javascript?

I'm not looking to push the values from one array into another, or concatenate them but simply sum the item values from each - either into a new array, or alternatively amending either arrayOne or arrayTwo with the values from the other e.g.
var arrayOne = [1,2,3,4,5]
var arrayTwo = [2,4,6,8,10]
// loop / function..
var newArray = [3,6,9,12,15]
OR arrayOne = [3,6,9,12,15]
I thought this would be straightforward but this requires 2 loops running at the same time?
Thanks for your help!
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = [];
newArray = arr1.map((item,index)=>{
return item + arr2[index]
});
You could collect all wanted array for adding values at the same index in an array and reduce the arrays.
This works with an arbitrary count of arrays.
var array1 = [1, 2, 3, 4, 5],
array2 = [2, 4, 6, 8, 10],
result = [array1, array2].reduce(
(a, b) => (b.forEach((v, i) => a[i] = (a[i] || 0) + v), a)
);
console.log(result);
You can use Array's map():
var arrayOne = [1,2,3,4,5];
var arrayTwo = [2,4,6,8,10];
var newArray = arrayOne.map( (item, i) => item += arrayTwo[i] );
console.log(newArray);

Transform a javascript array of object to an array of array

I am looking an elegant way in ES6 to transform this array:
var src = [{x:1,y:'a'},{x:2,y:'b'}];
To this array:
var desc = [[1,2],["a","b"]];
Which contains an array of all the properties and one array for all the values.
For this, i have written this code:
var src = [{x:1,y:'a'},{x:2,y:'b'}];
var prop1 = [];
var prop2 = [];
src.forEach(item => {
prop1.push(item.x)
prop2.push(item.y);
});
var desc = [prop1, prop2];
It works fine but it is quite long, so I am looking for an eventual improvement and a short code.
You name the props order (because the order of keys in object is not guaranteed) and then map over src array by extracting correspondend prop value.
var src = [{x:1,y:'a'},{x:2,y:'b'}]
var props = ['x', 'y'];
var result = props.map(prop => src.map(x => x[prop]))
console.log(result)
You can use .reduce():
let src = [{x: 1, y: 'a'}, {x:2, y: 'b'}];
let result = src.reduce((a, c) => (a[0].push(c.x), a[1].push(c.y), a), [[], []]);
console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Docs:
Array.prototype.reduce()
Array.prototype.push()
Comma Operator
You could iterate the array and then by the keys of the object and switch the outer and inner indices the target element.
var src = [{ x: 1, y: 'a' }, { x: 2, y: 'b' }],
desc = [];
src.forEach(o => Object.keys(o).forEach((k, i) => (desc[i] = desc[i] || []).push(o[k])));
console.log(desc);

How to filter duplicate sub-arrays of integers and strings from two dimensional array in Javascript

I am receiving a 2-dimensional array of both integers and strings, and I want to remove duplicates from them:
original array = [["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1], ,["admin"], [1], ["admin"]
expected result = [["admin", 2, "regular"], ["customer", "regular"], [1], ["admin"]]
Please how can I do this in Javascript?
Does it matter if your array (and it's sub-arrays) gets reordered? If it doesn't, then:
var array = [["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1],["admin"], [1], ["admin"]];
array = array.map(x => x.sort()).sort();
var uniqueArray = [];
uniqueArray.push(array[0]);
for (var i = 1; i < array.length; i++){
if (JSON.stringify(array[i]) != JSON.stringify(array[i-1])){
uniqueArray.push(array[i]);
}
}
console.log(uniqueArray);
You could sort a copy from the inner arrays and build a string and check against a hash table while filtering.
var array = [["admin", 2, "regular"], ["customer", "regular"], ["regular", "customer"], [1], ["admin"], [1], , ["admin"]],
object = Object.create(null),
unique = array.filter(function (a) {
var b = a.slice().sort().join('|');
return !object[b] && (object[b] = true)
});
console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Here is an algorithm that might help you. It is NOT javascript written.
And it does not do the difference between ["customer", "regular"] and ["regular", "customer"], but you have the general idea :
var newArray = [];
for(x in originalArray) { //travel in the original array
var flag = 1; //flag indicating if x is already in newArray
for(y in array) {
if(y == x) flag = 0; //if x already belongs to newArray
}
if(flag==1) newArray += x; //add if not already in newArray
flag = 1; //reset value of flag
}
Basically, you create a new array in which you add only value that do not already belong to it. Good luck :)

Sorting a numeric array along with an array of objects in JavaScript

Suppose I generate two arrays
One that holds Array of numbers:
[5.65, 3.25, 4.34, 6.78]
And another array that holds objects with some information in them
[car.object1, car.object2, car.object3, car.object4]
And the objects in second array are related to the numbers in first array. So object1 is related to 5.65, object2 to 3.25 and so on.
So I want to sort the array 1 in an ascending order and at the same time sort the array 2 also.
So the result should be:
[3.25, 4.34, 5.65, 6.78]
&
[car.object2, car.object3, car.object1, car.object4]
My Approach: (You can just ignore the below answer as I think it is wrong. It does not work.)
var all = [];
var A = [5.65, 3.25, 4.34, 6.78];
var B = ['store.object1', 'store.object2', 'store.object3', 'store.object4'];
for (var i = 0; i < B.length; i++) {
all.push({
'A': A[i],
'B': B[i]
});
}
all.sort(function(a, b) {
return a.A - b.A;
});
A = [];
B = [];
for (var i = 0; i < all.length; i++) {
A.push(all[i].A);
B.push(all[i].B);
}
console.log(A, B);
You could use a temporary array with the indices and sort it with the values of the first array. Then map the sorted array with the values of array1 and array2.
I use strings for the second array, instead of missing objects.
var array1 = [5.65, 3.25, 4.34, 6.78],
array2 = ['car.object1', 'car.object2', 'car.object3', 'car.object4'],
temp = array1.map(function (_, i) { return i; });
temp.sort(function (a, b) { return array1[a] - array1[b]; });
array1 = temp.map(function (a) { return array1[a]; });
array2 = temp.map(function (a) { return array2[a]; });
console.log(temp);
console.log(array1);
console.log(array2);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Unless you want to implement the sort yourself, one simple way is to combine the entries from the number array with the entries from the object array (at least briefly), sort that, and then (if necessary) extract the result:
// Setup
var car = {
object1: {name: "object1"},
object2: {name: "object2"},
object3: {name: "object3"},
object4: {name: "object4"}
};
var nums = [5.65, 3.25, 4.34, 6.78];
var objs = [car.object1, car.object2, car.object3, car.object4];
// Combine
var joined = [];
nums.forEach(function(num, index) {
joined[index] = {num: num, object: objs[index]};
});
// Sort
joined.sort(function(a, b) {
return a.num - b.num;
});
// Extract
nums = [];
objs = [];
joined.forEach(function(entry, index) {
nums[index] = entry.num;
objs[index] = entry.object;
});
console.log(nums);
console.log(objs);
.as-console-wrapper {
max-height: 100% !important;
}
But rather than combine, sort, and extract, I'd probably just maintain a single array and add each number to its relevant object, so they always travel together.
Here is an ES6 way to do it:
let a = [5.65, 3.25, 4.34, 6.78];
let b = [{ x:1 }, { x:2 }, { x:3 }, { x: 4}];
[a, b] = a.map( (n, i) => [n, b[i]] ) // zip the two arrays together
.sort( ([n], [m]) => n-m ) // sort the zipped array by number
.reduce ( ([a,b], [n, o]) => [[...a, n], [...b, o]], [[],[]] ); // unzip
console.log(JSON.stringify(a));
console.log(JSON.stringify(b));
I've helped myself with an object containing car.object as the key and it's number as the value. Seems easy&quick solution.
var obj = [{'car.object1': 5.65}, {'car.object2': 3.25}, {'car.object3': 4.34}, {'car.object4': 6.78}],
objs = obj.sort((a,b) => a[Object.keys(a)] - b[Object.keys(b)]);
console.log(objs.map(v => Object.keys(v)[0]));
console.log(objs.map(v => v[Object.keys(v)]));
console.log(objs);
.as-console-wrapper {
max-height: 100% !important;
}

Categories

Resources