how do I format my response array in angular? - arrays

Need to format my array for chart purpose
myArr=[["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]
Below Formatted Array
formatArr= [["6709", "1949", "87484", "12760"], ["13326", "3356", "98000", "16949"], ["29981", "7879", "117640", "30727"], ["122071", "21325", "210406", "65824"], ["2744807", "56664", "382719", "134578"] ["2440528", "83819", "1362744", "450092"], ["2461", "336", "166446", "16363"]]

You could reduce it like this for example:
const formatArr: string[][] = myArr.reduce((prev, item, index) => {
if (index % 4 === 0) {
// every fourth item creates a new array with the current item:
prev.push(item);
} else {
// every other item pushes to the previously added item:
prev[prev.length - 1].push(item[0]);
}
return prev;
}, [] as string[][]);

myArr = [["6709"],["1949"],["87484"],["12760"],["13326"],["3356"],["98000"],["16949"],["29981"],["7879"],["117640"],["30727"],["122071"],["21325"],["210406"],["65824"],["2744807"],["56664"],["382719"],["134578"],["2440528"],["83819"],["1362744"],["450092"],["2461"],["336"],["166446"],["16363"]]
formatArr = []
function makeArray(params) {
let element = [];
for (let i = 0; i < myArr.length; i++) {
element.push(myArr[i][0])
if ((i + 1) % 4 == 0) {
formatArr.push(element);
element = [];
}
}
console.log(formatArr);
}
makeArray();
This is correct if myArr has 4n element, if not use this
function makeArray(params) {
let element = [];
for (let i = 0; i < myArr.length; i++) {
element.push(myArr[i][0])
if ((i + 1) % 4 == 0) {
formatArr.push(element);
element = [];
}
if (i == myArr.length - 1 && (i + 1) % 4 != 0) {
formatArr.push(element);
}
}
console.log(formatArr);
}

Related

Filter an array for even strings

I want the function to return strings of equal length, which it does but I also want it to remove non-strings and strings of odd length. Can anyone help?
function evenLength(items) {
let evenNumber = items.filter(items => {
if(items % 2 != 0){
return true;
}
});
return(evenNumber)
}
In order to check for parity and check if the array element is a string you can do the following:
function checkForParityAndStringType(data) {
var result = [];
for (let i = 0;i < data.length; i++) {
const elem = data[i];
// remove non string
if (typeof elem !== 'string') continue;
// Length is not even
if (elem.length % 2 !== 0) continue;
result.push(elem)
};
return result
}

All possible combinations across arrays in nodejs

Lets say I have three arrays:
var arr1 = ['red', 'orange', 'yellow',];
var arr2 = ['car', 'bus'];
var arr3 = ['china'];
How to get the following combinations:
1. Order matters,
2. Each result(can be a array) should contain 0..1 element of each arr
3. Element of arr1,arr2,arr3 can appear 0..1 times :
red,car,china
red,china,car
car,red,china
car,china,red
china,car,red,
china,red,car
red,bus,china
red,china,bus
bus,red,china
bus,china,red
china,bus,red,
china,red,bus
orange,car,china
orange,china,bus
bus,orange,china
bus,china,orange
china,bus,orange,
china,orange,bus
orange,bus,china
orange,china,bus
bus,orange,china
bus,china,orange
china,bus,orange,
yellow,car,china
yellow,china,car
car,yellow,china
car,china,yellow
china,car,yellow,
china,yellow,car
yellow,bus,china
yellow,china,bus
bus,yellow,china
bus,china,yellow
china,bus,yellow,
china,yellow,bus
red,car
car,red
red,bus
bus,red
orange,car
car,orange,
orange,bus
bus,orange,
yellow,car
car,yellow,
yellow,bus
bus,yellow,
red,china
china,red,
orange,china
china,orange,
yellow,china
china,yellow,
car,china
china,car,
bus,china
china,bus,
red,
orange,
yellow,
car,
bus,
china,
What I could not figure out is how to control the appear times in the element of each arr, my code is as follows:
function get_titles_appearances(titles_columns) {
titles_columns = titles_columns || [];
var n = titles_columns.length;
if (n === 0) { return [] }
if (n === 1) { return titles_columns[0] }
var save = function () {
var m = groups.length, c = [];
while (m--) { c[m] = groups[m] }
rtn.push(c);
}
var i = 0, len = 0, counter = [], groups = [], rtn = [];
for (; i < n; i++) {
counter[i] = 0;
groups[i] = titles_columns[i][0];
}
save();
while (true) {
i = n - 1, len = titles_columns[i].length;
if (++counter[i] >= len) {
while (counter[i] >= len) {
if (i === 0) { return rtn }
groups[i] = titles_columns[i][0];
counter[i--] = 0;
counter[i]++;
len = titles_columns[i].length;
}
}
groups[i] = titles_columns[i][counter[i]];
save();
}
}
_.forEach(get_titles_appearances(titles_columns_config_default), function (value) {
// titles_appearances.push( _.join(value, '')+"':'"+_.join(value, ','))
titles_appearances = titles_appearances+"{"+ _.join(value, '')+":"+_.join(value, ',')+"},"
})
titles_columns_config_default refer to [arr1,arr2,arr3]

Typescript sorting array with objects on multiple properties

I like to sort an array with objects that have multiple properties. My objects have a string called name and a boolean called mandatory.
First i want to sort on age, next on the name.
How do I do this?
Ordering by age is easy...:
this.model.mylist.sort((obj1: IObj, obj2: IObj => {
if (obj1.age < obj2.age) {
return -1;
}
if (obj1.age > obj2.age) {
return 1;
}
return 0;
});
Well, you only add comparation for case when the two age values are the same. So something like this should work:
this.model.mylist.sort((obj1: IObj, obj2: IObj) => {
if (obj1.age < obj2.age) {
return -1;
}
if (obj1.age > obj2.age) {
return 1;
}
return obj1.name.localeCompare(obj2.name);
});
Something like this should work. The method compares the current and next values and adds comparison to the case when the two age values are the same. Then assume the column name in order based on age.
private compareTo(val1, val2, typeField) {
let result = 0;
if (typeField == "ftDate") {
result = val1 - val2;
} else {
if (val1 < val2) {
result = - 1;
} else if (val1 > val2) {
result = 1;
} else {
result = 0;
}
}
return result;
}
-
this.model.mylist.sort((a, b) => {
let cols = ["age", "name"];
let i = 0, result = 0, resultordem = 0;
while (result === 0 && i < cols.length) {
let col = cols[i];
let valcol1 = a[col];
let valcol2 = b[col];
let typeField = "string";
if (col == "age") {
typeField = "number";
}
if (valcol1 != "null" && valcol1 != "null") {
resultordem = this.compareTo(valcol1, valcol2, typeField);
if (resultordem != 0) {
break;
}
}
i++;
}
return resultordem;
});

Search an array for a string and return the index in AS3

I want to search an array to see if it contains a specific string, and then get the index of the result.
For example, if I had:
array[0] = "dogs";
array[1] = "cats";
array[2] = "oranges";
I want to be able to search for "oran" and get 2 back. Any idea on how to do this?
You can do something like this:
function findInArray(str:String):int {
for(var i:int = 0; i < array.length; i++){
if(array[i] == str){
trace("found it at index: " + i);
return i;
}
}
return -1; //If not found
}
Then whenever you want to find something call it like:
findInArray("oranges"); // Returns 2
To search for a part of the word can pontentially return undesiderd results for bigger lists, but you can do it with the following:
function findInArrayPartially(str:String):int {
for(var i:int = 0; i < array.length; i++){
if(array[i].indexOf(str) > -1){
trace("found it at index: " + i);
return i;
}
}
return -1; //If not found
}
Another way to do it:
var arr:Array = ["dogs", "cats", "oranges", "apples"];
function indexOfSubstring(array:Array, stringToFind:String):int
{
var answer:int = array.indexOf(stringToFind);
if (answer == -1)
{
var separator:String = "|";
var arrayToString:String = array.join(separator);
var indexInString:int = arrayToString.indexOf(stringToFind);
if (indexInString != -1)
{
var shorterStr:String = arrayToString.substring(0, indexInString);
answer = shorterStr.split(separator).length - 1;
}
}
return answer;
}
trace(indexOfSubstring(arr, "oran")); // returns 2
trace(indexOfSubstring(arr, "les")); // returns 3
trace(indexOfSubstring(arr, "ts")); // returns 1
trace(indexOfSubstring(arr, "broom")); // returns -1

Sorting an array to avoid neighboring items having duplicate attributes

I have an array of objects. Each object has a color attribute which could be "red", "blue", "yellow", "green", "orange" or "purple". There are 20-30 objects in the array so colors repeat. My goal is to sort the array so that no colors are next to each other. Distribution of colors is not exactly even but close.
This is what I have so far. It checks the next and previous object for a color match and if it finds a match it moves it to the end of the array.
private function sortColors():void
{
var getNext:uint;
var getPrev:uint;
var maxCount:uint = colorArray.length;
for (var i:uint = 0; i < maxCount; i++) {
var cur:ValueObject = colorArray[i];
(i == maxCount-1) ? getNext = 0 : getNext = i+1;
(i == 0) ? getPrev = maxCount-1 : getPrev = i-1;
var next:ValueObject = colorArray[getNext];
var prev:ValueObject = colorArray[getPrev];
if (cur.color == next.color) {
var move:ValueObject = colorArray[getNext];
colorArray.splice(getNext, 1);
colorArray.push(move);
}
if (cur.color == prev.color) {
var move:ValueObject = colorArray[getPrev];
colorArray.splice(getPrev, 1);
colorArray.push(move);
}
}
}
This works OK but if there is more of a certain color they end up repeating at the end. I could add something to the end to throw those back into the mix but I feel like there must be a better way. Someone enlighten me.
Try:
var colorObjects:Array = [/* list of objects with colors - populated below*/];
var jumbled:Array = [];
var lastColor:String = "";
function getDifferentTile():void
{
if(lastColor.length == 0)
{
jumbled.push(colorObjects.pop());
lastColor = jumbled[0].mycolor;
}
else
{
var i:Object;
for each(i in colorObjects)
{
var repeat:uint = 0;
if(i.mycolor != lastColor)
{
jumbled.push(i);
lastColor = i.mycolor;
colorObjects.splice(colorObjects.indexOf(i), 1);
return;
} else {
repeat++;
}
if (repeat > 0 && repeat == colorObjects.length) {
jumbled.push(i);
colorObjects.splice(colorObjects.indexOf(i), 1);
return;
}
}
}
}
// list of random colors
var colors:Array = ["0x000000","0x444444","0xFFFFFF","0xFF00FF"];
// prepare random array for test
var i:uint = 0;
for(i; i<100; i++)
{
var obj:Object =
{
mycolor: colors[uint(Math.random()*colors.length)]
};
colorObjects.push(obj);
}
// fill the jumble array until the original listing is empty
while(colorObjects.length > 0)
{
getDifferentTile();
}
// output jumbled
var j:Object;
for each(j in jumbled)
{
trace(j.mycolor);
}

Resources