How to create sub array from array - javascript

I have large data structure to manipulate and I have some problems sorting similar data into sub array.
var arr = [2016-12-16, 2016-12-16, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-18, 2016-12-18, 2016-12-19];
I wanna sort like this.
[[2016-12-16, 2016-12-16], [ 2016-12-17, 2016-12-17, 2016-12-17, 2016-12-17],[2016-12-18, 2016-12-18] [2016-12-19]]

Array#reduce the array into an array of arrays by using a object as a hash:
var arr = ['2016-12-16', '2016-12-16', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-17', '2016-12-18', '2016-12-18', '2016-12-19'];
var result = arr.reduce(function(r, item) {
(r.hash[item] || (r.hash[item] = r.arr[r.arr.push([]) - 1])).push(item);
return r;
}, { arr: [], hash: {} }).arr;
console.log(result);

The easiest way to do this is with a dictionary (which JS objects naturally act as).
var datesArray = [ "2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19" ]; //I've corrected the syntax for this to make each date a string, rather than a sequence of subtractions
var datesCount = {};
datesArray.forEach(function(date){
if(!datesCount[date])
datesCount[date] = []
datesCount[date].push(date);
});
At this point, you have a set of group arrays, each containing every instance of a particular date. You can iterate over it with Object.getOwnPropertyNames and put each array into the larger array OR you could just use it directly.

try to divide the code to sub problems-
first, convert all element to strings (before writing a function).
copy the array to manipulate without changing original.
sort elements.
identify repeated elements.
create sub arrays for repeated elements.
this a code I've written for a differend purpose and modified it for the explanation.
there might be more effient ways to write it, i'm still learning..
const dateStringSort = (array) => {
//assign to a new array - wont change exist array
const arr = [].concat(array);
//sort elements
arr.sort();
//identify repeated elements and group them to sub arrays.
const arr1 = []; //assign another array to prevent inifinty loops
while (arr.length>0){
let i = arr[0];
let filtered = arr.filter(item=>item===i);//return new array with all reapeted elements
arr1.push(filtered); //push the filtered array to new array as a sub array
arr.splice(0,(filtered.length)); //delete all the repeated elements from arr to prevent double sub araays
};
//return new array
return arr1;
};
//run function
const originArray = ["2016-12-16", "2016-12-16", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-17", "2016-12-18", "2016-12-18", "2016-12-19"];
const newArray = dateStringSort(originArray);

Related

Add array inside array in Javascript

How do I push array into a new Array.
For example
var arr = ['one','two','three'];
var newArr = [];
Now I want newArr[0] = ['one','two','three']
I have tried using push function but it pushes all the elements of arr into newArr. I want to push the entire arr as it is in newArr
var arr = ['one','two','three'];
var newArr = [];
newArr.push(arr); //<-- add entire original array as first key of new array
You can write:
newArr[0] = ['one','two','three'];
And this will work. Or use variable:
newArr[0] = arr;
Also, array methods push or unshift will the same way in your situation work:
newArr.push(arr);
Others have answered, so I guess your question is not really clear.
As you put your question, first and only element of newArray should be the arr array, then you use
newArr.push(arr);
as Mitya and Tiij7 said.
However, maybe you meant you want to join (concat) 2 arrays in a new array? Then you would use:
var arr3 = [].concat(arr, newArr);
or
var arr3 = [...arr, ...newArr];
Or you just wanted to clone the initial array? Then use
var newArr = [...arr];

Sorting multidimensional array based on multiple criteria

I'm trying to figure out an efficient method to sort a multidimensional array based on how many values of another array exist.
Given the following array:
[1,2,3,4,5,6,7,8,9,10]
I am trying to sort another array of arrays based on how many of those values are included.
[
[1,3,5,7,9,22],
[1,200,300,400,500,600],
[1,2,3,4,5,6]
]
So the code I'm trying to get to would return:
[
[1,2,3,4,5,6],
[1,3,5,7,9,22],
[1,200,300,400,500,600]
]
I think what I'm doing is very inefficient and could be written better or more succinctly with a method I'm not aware of?
https://jsfiddle.net/gb3fsLdv/
const compareNums = [1,2,3,4,5,6,7,8,9,10];
let ourData = [
[1,2,3,100,200,300],
[100,200,300,400,500,600],
[1,2,3,5,6,9]
];
function sortArr(compare, data){
let indexMatches = [];
data.map(arr => {
let count = 0;
compare.map(num => {
if(arr.includes(num)){
count++
}
})
indexMatches.push(count);
})
// So now I have indexMatches with a count of how many hits each array has in the correct index order as the original data
// And I can use data to sort them based on these values...
// Little stuck how to relate the two so the same sorting happens to both arrays
}
sortArr(compareNums, ourData);
First convert the given array to set. And then use filter() to get the count of elements included in other array
const data = [
[1,3,5,7,9,22],
[1,200,300,400,500,600],
[1,2,3,4,5,6]
]
let arr = [1,2,3,4,5,6,7,8,9,10];
function getCount(arr, set){
return arr.filter(x => set.has(x)).length
}
function sortOnCount(data, arr){
let set = new Set(arr);
return data.slice(0).sort((a, b) => getCount(b, set) - getCount(a, set))
}
console.log(sortOnCount(data, arr))

Convert array with 5 items into array with 1 item

I have an array called 'xxx' with contains 5 items.
I would like to convert it in to a single array with the name newTableData[].
What is the best way to do this?
You can assign array with 5 elements to the zeroth element of second array
var newArray = [];
newArray[0] = existingArray;
var cars = ["Audi", "Volvo", "BMW", "Bentley", "Maruti"];
var newArray = [];
newArray[0] = cars;
console.log(newArray);
For flattening your initial array, you can just do
const flattenedArray = [].concat.apply([], oldArray);
const newArray = [flattenedArray];
If I'm right, the problem is that you have an Array of Arrays of TableItems. Just use a reduce and concat:
xxx.reduce((acc, arrayWithTableItem) => acc.concat(arrayWithTableItem), []);
This way you take advantage of the fact that concat flattens a single level down, so from this:
[[TableItem], ...[TableItem]]
you end up with
[TableItem, ...TableItem]
It's easy peas from there
[xxx.reduce((acc, x) => acc.concat(x), [])]
if you are using ES6+ you can use array destructuring ...
cont newTableData[0] = [...xxx];

Javascript - Rearrange array elements in ascending order of elements within each array

I have an array:
arr =
[{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]}]
arr consists of 6 elements. Each of these six elements consists of another array keys. I need to rearrange the six elements in ascending order of the number of keys within each. This means that I need the array to be rearranged in this manner:
arr =
[
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]},
{"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
]
I tried to get the number of elements within keys of each array element as shown in the code below:
var arrMap = [];
arr.forEach(function(array_) {
key_ = array_.keys;
var count = 0;
key_.forEach(function(arrKey) {
count++;
var keyCode = arrKey.sid;
})
arrMap.push({'nid':array_.nid, 'count': count});
})
console.log(arrMap);
This gave me the following output:
[{"nid":"MIA","count":2},{"nid":"MID","count":1},{"nid":"MIT","count":10},{"nid":"MIO","count":3},{"nid":"MIS","count":2},{"nid":"MIH","count":1}]
Now I am confused as to how I can proceed to rearrange the array using the count of key elements. Any guidance/help would be highly appreciated!
You can try .sort
let arr = [ {"nid":"MIA","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MID","keys":[{"sid":"sm1"}]},
{"nid":"MIT","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"},{"sid":"sm4"},{"sid":"sm5"},{"sid":"sm6"},{"sid":"sm7"},{"sid":"sm8"},{"sid":"sm9"},{"sid":"sm10"}]},
{"nid":"MIO","keys":[{"sid":"sm1"},{"sid":"sm2"},{"sid":"sm3"}]},
{"nid":"MIS","keys":[{"sid":"sm1"},{"sid":"sm2"}]},
{"nid":"MIH","keys":[{"sid":"sm1"}]} ];
arr.sort((a, b) => a.keys.length - b.keys.length);
console.log(arr);
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
You can achieve this by using sort function of array
arr.sort(function(a,b){return a.keys.length - b.keys.length})

How to collect / make new array by existing arrays label wise?

How to create new array from slicing the existing array by it's key?
for example my input is :
var array = [{"one":"1"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},
{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},
{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},
{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},
{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005"} ];
my output should be :
var outPutArray = [
{"one" : ["1","01","001","0001","00001"]},
{"two":["2","02","002","0002","00002"]},
{"three":["3","03","003","0003","00003"]},
{"four":["4","04","004","0004","00004"]},
{"five":["5","05","005","0005","00005"]}
]
is there any short and easy way to achieve this in javascript?
You can first create array and then use forEach() loop to add to that array and use thisArg param to check if object with same key already exists.
var array = [{"one":"1","abc":"xyz"},{"one":"01"},{"one":"001"},{"one":"0001"},{"one":"00001"},{"two":"2"},{"two":"02"},{"two":"002"},{"two":"0002"},{"two":"00002"},{"three":"3"},{"three":"03"},{"three":"003"},{"three":"0003"},{"three":"00003"},{"four":"4"},{"four":"04"},{"four":"004"},{"four":"0004"},{"four":"00004"},{"five":"5"},{"five":"05"},{"five":"005"},{"five":"0005"},{"five":"00005","abc":"xya"} ];
var result = [];
array.forEach(function(e) {
var that = this;
Object.keys(e).forEach(function(key) {
if(!that[key]) that[key] = {[key]: []}, result.push(that[key])
that[key][key].push(e[key])
})
}, {})
console.log(result);
var outputArray=[array.reduce((obj,el)=>(Object.keys(el).forEach(key=>(obj[key]=obj[key]||[]).push(el[key])),obj),{})];
Reduce the Array to an Object,trough putting each Arrays object key to the Object as an Array that contains the value.
http://jsbin.com/leluyaseso/edit?console

Categories

Resources