I am having following object structure
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
Expected output is:
result = [["direct","indirect"],["indirect","dir"],["dir","indir"]];
What I have tried:
var result = [];
var array = [];
for(var key in obj){
if(array.length <2) {
array.push(obj[key]);
}else{
array =[];
array.push(obj[key-1]);
}
if(array.length == 2){
result.push(array);
}
}
console.log(result);
I am getting the output as follows:
result = [["direct", "indirect"], ["indirect", "indir"]]
If they're all strings that have at least one character, then you can do this:
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];
for (var i = 1; obj[i]; i++) {
result.push([obj[i-1], obj[i]]);
}
It starts at index 1 and pushes the current and previous items in an Array. It continues as long as the values are truthy, so if there's an empty string, it'll stop.
If there could be falsey values that need to be included, then you should count the properties first.
var obj = {"0":"direct","1":"indirect","2":"dir","3":"indir"};
var result = [];
var len = Object.keys(obj).length;
for (var i = 1; i < len; i++) {
result.push([obj[i-1], obj[i]]);
}
Related
I'm trying to create an array of strings and produce the possibilities by the length of array string. For example:
var someStr = ["a","b","c","d"];
//I want to produce this outcome
a
ab
abc
abcd
b
bc
bcd
c
cd
d
I know I can get the # of possibilities for "a" only by this way:
var numCombinations = 0;
var comboString = '';
var outcome = [];
for(var i = 0; i < someStr.length; i++){
comboString += someStr[i];
outcome[i] = comboString;
numCombinations += i; //# of combinations from above
}
But how would I continue with these variables for the left over possibilities? I've thought of creating nested for-loops again and again but that would eventually lead to the (n)th length with hard-coding. Would there be any method(s) to create this and store all the possibilities to the (n)th length?
Hope this help.
function getComboStringListFromIdx(arr, idx){
var result = [];
var comboString = '';
for(var i=idx; i<arr.length; i++){
comboString += arr[i];
result.push(comboString);
}
return result;
}
var someStr = ['a','b','c','d'];
var outCome = [];
for(var i = 0; i<someStr.length; i++){
outCome = outCome.concat(getComboStringListFromIdx(someStr, i));
}
I will also use nested for-loop ! One is normal looping and other is to skip less than current index from first loop !!
var someStr = ["a","b","c","d"];
for(var i = 0;i < someStr.length;i++) {
output(i);
}
function output(index) {
var str = "";
for(var j in someStr) {
if(j < index) {
continue;
}
str += someStr[j];
console.log(str);
}
}
This solution uses a nested for loop and skips concatenation on the first element of the nested for loop.
var arr = ["a","b","c","d"];
for(var i=0;i<arr.length;i++){
var str = arr[i];
for(var j=i;j<arr.length;j++){
if(i!==j)
str+=arr[j];
console.log(str);
}
}
https://jsfiddle.net/fmy539tj/
I have two arrays like below
var arr = ["x", "y", "z", "a", "b", "c"];
var tgtArr = [{val:"a"}, {val:"b"}]; It does not need to be as lengthy as Array `arr`
This is what I have tried
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
for(var k = 0; k < tgtArr.length; k++){
dest[i] = dest[i] || [];
if(tgtArr[k].val == arr[i]){
dest[i] = arr[i];
}
}
}
console.log(dest);
My Expected output is (for above tgtArr value)
[{}, {}, {}, {val:"a"}, {val:"b"}, {}];
if tgtArr is empty Array
[{},{},{},{},{},{}]
Here is the fiddle. Any alternative for this, it seems not a good way to me as I am iterating through the entire array everytime.
Short:
var result = arr.map(function(x) {
return tgtArr.some(function(o) { return o.val == x; }) ? {val:x} : {};
});
This is more efficient:
var set = {};
tgtArr.forEach(function(obj, i) {
set[obj.val] = true;
});
var result = arr.map(function(x) {
return x in set ? {val:x} : {};
});
This is the same as Paul's answer, but with a loop instead of map. It collects the keys first based on the val property, then creates a new array either with empty objects if the key isn't in tgtArr, or copies a reference to the object from tgtArr if it is:
function newArray(arr, tgtArr) {
var keys = {},
i = tgtArr.length,
j = arr.length,
newArr = [];
// Get keys
while (i--) keys[tgtArr[i].val] = tgtArr[i];
// Make new array
while (j--) newArr[j] = arr[j] in keys? keys[arr[j]] : {};
return newArr;
}
It should be efficient as it only traverses each array once.
var dest = new Array(arr.length);
for(var i = 0; i < arr.length; i++){
dest[i] = {}
for(var k = 0; k < tgtArr.length; k++){
if(tgtArr[k].val == arr[i]){
dest[i] = tgtArr[k];
}
}
}
console.log(dest);
I like using map rather than loops for this kind of thing (Fiddle):
var result = arr.map(function(x) {
var match = tgtArr.filter(function(y) {
return y.val == x;
});
if (match.length == 1) return match[0];
else return {};
});
This is a possibly inefficient, in that it traverses tgtArr for every item in arr, so O(n*m). If needed, you could fix that by pre-processing tgtArr and converting it to a hash map (Fiddle). This way you've got an O(n+m) algorithm (traverse each array once):
var tgtMap = {};
tgtArr.forEach(function(x) { tgtMap[x.val] = x; })
var result = arr.map(function(x) {
var match = tgtMap[x];
return match || {};
});
var tmp = {};
for (var i = 0; i < tgtArr.length; i++) {
tmp[tgtArr[i].val] = i;
}
var dest = [];
for (var i = 0; i < arr.length; i++) {
var obj= tmp[arr[i]] === undefined ? {} : tgtArr[tmp[arr[i]]];
dest.push(obj);
}
DEMO
I have an array (tlist) with keys linked with arrays:
tliste.push({"GROUP104":["321992","322052","321812","314022","0"]});
tliste.push({"GROUP108":["322011","322032","0"]});
tliste.push({"GROUP111":["322020","322021","322040","322041","313060","313072","0"]});
I now need to build a function to take the values of e.g. Group104 and Group111 and clone these into a new array:
newarrray = ["321992","322052","321812","314022","0","322020","322021","322040","322041","313060","313072","0"]
Preferably the new array should be ordered and the "0" should be removed - but that is of lower importance.
Let the groups to be extracted be grp[].
You can do something like this -
// Extract groups in grp[] from origArray[]
var extractGrps = function(grps, origArray) {
var result = [];
for(var i =0; i<grps.length; i+=1) {
var indxInOrigArray = indexOfObjectWithKey(origArray, grps[i]);
if(indxInOrigArray > 0) {
var arrLocal = origArray[indxInOrigArray].grps[i];
for(var j=0; j<arrLocal.length;j+=1)
result.push(arrLocal[j]);
}
}
return result;
}
//find Index of object in arr whose key matches the given input key
var indexOfObjectWithKey = function(arr, key) {
for(var i=0; i<arr.length; i+=1) {
if(arr[i].key) {
return i;
}
}
return -1;
}
I'd like to split a string ("1,2,3") and return it as an int array so I wrote the following function:
function stringToIntArray(string) {
var split = {};
split = string.split(',');
var selected = {};
for (var i = 0; i <= split.length; i++) {
selected[i] = split[i];
}
return selected;
}
However split.length is always undefinied. Where's my mistake?
var selected = {};
doesn't build an array but an object, which has no length property.
You can fix your code by replacing it with
var selected = [];
If you want to return an array of numbers, you can change your code to
function stringToIntArray(string) {
var split = string.split(',');
var selected = [];
for (var i = 0; i < split.length; i++) {
selected.push(parseInt(split[i], 10));
}
return selected;
}
Note that I replaced <= with < in your loop.
Note also that for modern browsers, you can use the map function to make it simpler :
function stringToIntArray(string) {
return string.split(',').map(function(v){ return parseInt(v, 10) });
}
I want to create an array like this:
s1 = [[[2011-12-02, 3],[2011-12-05,3],[5,13.1],[2011-12-07,2]]];
How to create it using a for loop? I have another array that contains the values as
2011-12-02,3,2011-12-05,3,2011-12-07,2
One of possible solutions:
var input = ['2011-12-02',3,'2011-12-05',3,'2011-12-07',2]
//or: var input = '2011-12-02,3,2011-12-05,3,2011-12-07,2'.split(",");
var output = [];
for(i = 0; i < input.length; i += 2) {
output.push([t[i], t[i + 1]])
}
If your values always come in pairs:
var str = '2011-12-02,3,2011-12-05,3,2011-12-07,2',//if you start with a string then you can split it into an array by the commas
arr = str.split(','),
len = arr.length,
out = [];
for (var i = 0; i < len; i+=2) {
out.push([[arr[i]], arr[(i + 1)]]);
}
The out variable is an array in the format you requested.
Here is a jsfiddle: http://jsfiddle.net/Hj6Eh/
var s1 = [];
for (x = 0, y = something.length; x < y; x++) {
var arr = [];
arr[0] = something[x].date;
arr[1] = something[x].otherVal;
s1.push(arr);
}
I've guessed here that the date and the other numerical value are properties of some other object, but that needn't be the case...
I think you want to create an array which holds a set of arrays.
var myArray = [];
for(var i=0; i<100;i++){
myArray.push([2011-12-02, 3]); // The values inside push should be dynamic as per your requirement
}