I would like to use the $.each() loop to iterate over digits in an integer.
The integer is produced as the index of another array, though I'm not sure that this makes a difference.
Javascript
var words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
var numbers = [];
$.each(words, function(i,word) {
$.each(i, function(index,value) {
$(numbers).append(value);
});
});
I would like the array numbers to equal the following array:
[ 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 1, 0, 1, 1 ]
Where the last four entries, [ ... 1, 0, 1, 1 ] are generated through iteration over the indexes for the entries [ ... "than", "ten." ] in the words array.
let words = [ "This", "is", "an", "array", "of", "words","with", "a", "length", "greater", "than", "ten." ];
let numbers = words.map((w, i) => i.toString().split('').map(Number)) //map into array of digits
numbers = Array.prototype.concat.call(...numbers); //concat them all
console.log(numbers);
Related
I've an array which has objects inside it:
[
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
I would like to join all the strings i.e pointName like this : "One-Two-Three"
Any help is appreciated. Thanks.
Edit 1:
This is what I tried so Far:
this.viaPoints.forEach(x=> {
var splitted = x.pointName.split(" ");
console.log('I5: ',splitted[0].join("-"));
});
The reason I've split is because the string will have extra characters some times like "One - A". So I've used split to remove the extra
Edit 2:
In my case this helped as I mentioned above that to remove extra characters and strings:
var permittedValues1 = this.viaPoints.map(value => value.pointName.split(" ")[0]).join("-") ;
You can use .map and .join functionalities too. Here .map will take the values based upon the key-pointName and .join is used to return an array as a string. The elements will be separated by a specified separator (here "-").
let array = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
];
var permittedValues = array.map(value => value.pointName).join("-") ;
You can use Array.prototype.reduce function to return an array which contains pointName for each object in the array and join all value of the return array with -.
let data = [
{pointID: 1, pointName: "One" },
{pointID: 2, pointName: "Two" },
{pointID: 3, pointName: "Three" }
]
let result = data.reduce((accumulator, current) => {
return accumulator.concat(current.pointName);
}, []).join('-');
console.log(result);
I have an array which is like :
const my_array = [
"S T"
"O P"
"Lend"
"GT"
"CT"
"AC"
];
and an object according to which this array is being reordered:
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
for which there is already a solution done as
//keys and sortBy from Lodash
const new_array = keys(my_array);
return sortBy(new_array, ar => AN_ORDER[ar] || Number.MAX_SAFE_INTEGER);
this yields me new array as:
["Lend", "AC", "O P", "S T", "GT", "C T"]
I tried looking into documentation of this usage, but I do not understand the idea of second argument being used here in sortBy.
Now my need is to reorder the my_array in below sequence:
['Lend', 'C T', 'S T', 'GT', 'AC', 'O P']
Please help me understand the implementation and suggest a way I can reorder in the same logic.
Your key 'G T' is not in object 'AN_ORDER' so my output will look different than yours. but it's working right.
const myArray = [
'S T',
'O P',
'Lend',
'GT',
'C T',
'AC'
];
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
const sortedCollection = _.sortBy(myArray, item => {
return AN_ORDER[item];
});
You have add array in second argument, here you can mention callback function or property name.
Here is the working solution
const my_array = [
"S T",
"O P",
"Lend",
"GT",
"C T",
"AC"
];
var AN_ORDER = {
"Lend": 1,
"C T": 2,
"S T": 3,
"AC": 4,
"O P": 5
};
console.log(_.sortBy(my_array, [a => {
return (AN_ORDER[a] || Number.MAX_SAFE_INTEGER);
}]));
<script src="https://cdn.jsdelivr.net/npm/lodash#4.17.15/lodash.min.js"></script>
Not sure what AN_ORDER represents, as there isn't enough information on what it represents exactly.
Uses the keys in AN_ORDER in the final array, because the specified output above uses that. Strips spaces before searching for matching keys, using a Set to search if they exist, and using an offset of 0.5 to insert non-existing keys into AN_ORDER for sorting.
const my_array = [
"S T",
"O P",
"Lend",
"GT",
"CT",
"AC"
];
const AN_ORDER = {
'Lend': 1,
'C T': 2,
'S T': 3,
'AC': 4,
'O P': 5
};
const keys = new Set(Object.keys(AN_ORDER).map(x=>x.replace(/\s/g,'')))
my_array.forEach( (x,i)=>!keys.has(x.replace(/\s/g,'')) && (AN_ORDER[x]=i+0.5) )
my_obj = _.sortBy(Object.entries(AN_ORDER), ([,x])=>x).map(([x,])=>x)
console.log(my_obj);
<script src="https://cdn.jsdelivr.net/npm/lodash/lodash.min.js"></script>
I am trying to pass a function that removes duplicates from an array. It should handle strings, object, integers as well. In my code so far I am showing that it will handle strings but nothing else. How can Imake this function universalto handle numbers,handle arrays,handle objects, and mixed types?
let unique = (a) => a.filter((el, i ,self) => self.indexOf(el) ===i);
In this function I hav unique() filtering to make a new array which checks the element and index in the array to check if duplicate. Any help would be appreciated.
i think the first you should do is to sort the array ( input to the function ). Sorting it makes all the array element to be ordered properly. for example if you have in an array [ 1, 3, 4, 'a', 'c', 'a'], sorting this will result to [ 1 , 3 , 4, 'a', 'a' , 'c' ], the next thing is to filter the returned array.
const unique = a => {
if ( ! Array.isArray(a) )
throw new Error(`${a} is not an array`);
let val = a.sort().filter( (value, idx, array) =>
array[++idx] != value
)
return val;
}
let array = [ 1 , 5, 3, 2, "d", "q", "b" , "d" ];
unique(array); // [1, 2, 3, 5, "b", "d", "q"]
let obj = { foo: "bar" };
let arraySize = array.length;
array[arraySize] = obj;
array[arraySize++] = "foo";
array[arraySize++] = "baz";
array[arraySize++] = obj;
unique(array); // [1, 2, 3, 5, {…}, "b", "baz", "d", "foo", "hi", "q"]
it also works for all types, but if you pass in an array literal with arrays or objects as one of its element this code will fail
unique( [ "a", 1 , 3 , "a", 3 , 3, { foo: "baz" }, { foo: "baz" } ] ); // it will not remove the duplicate of { foo: "baz" } , because they both have a different memory address
and you should also note that this code does not return the array in the same order it was passed in , this is as a result of the sort array method
Try using sets without generics. You can write a function as
Set returnUnique(Object array[]) {
Set set=new HashSet();
for (Object obj:array) {
set.add(obj);
}
return set;
}
I have an array which is built from data dynamically, so it can change.
It's basically this:
["t1", "something", "bird", "dog", "cow", "fish"]
What I need to do is to count how many of them there are and create another array with the same amount of columns but all with the value of 1.
For example, if the array is:
["bird", "dog", "cow", "fish"]
then it creates an array of:
[1, 1, 1, 1]
If the array is:
["bird", "fish"]
then it creates an array of:
[1, 1]
How can I do this?
You can use the Array.prototype.map method:
var input = ["foo", "bar", "baz"];
var mapped = input.map(function () { return 1; });
Just create a new array of equal length and use the fill function.
var myArray = ["dog","cat","monkey"];
var secondArray = new Array(myArray.length).fill(1);
// es6
var array = ["t1", "something", "bird", "dog", "cow", "fish"]
array.map(() => 1); // => [1, 1, 1, 1, 1, 1]
// if you don't care if they are strings
'1'.repeat(array.length).split(''); //=> ["1", "1", "1", "1", "1", "1"]
Is this the way to create and obj to store multiple values, if so, how would you randomly choose two or three values without repeating again until all values were outputted from the array?
I want to randomly get the values like this
E.g., if row three was randomly chosen then the results should be;
gg hh ee
I.e., I want to randomly output one array with its values, that would be like three hints for a question, so, the user would have to enter the answer and then compare the values to see if it matches.
JS
var list = {
"one": [ { "a": "aa", "b": "bb", "c":"cc" } ],
"two": [ { "d": "dd", "e": "ee", "f":"ff" } ],
"three": [ { "g": "gg", "h": "hh", "e":"ee" } ],
"four": [ { "j": "jj", "k": "kk", "l":"ll" } ],
"five": [ { "m": "mm", "n": "nn", "o":"oo" } ]
};
And also if I decide just to output one value at a time, how can I do that?
Currently if row three was randomly selected it would output an array with one entry (your object), like so:
[[object Object] {
e: "ee",
g: "gg",
h: "hh"
}]
We can just use arrays and the Fisher-Yates function, which can be found here: https://github.com/coolaj86/knuth-shuffle
This should give us a randomized array of the values.
function shuffle(array) {
var currentIndex = array.length, temporaryValue, randomIndex ;
// While there remain elements to shuffle...
while (0 !== currentIndex) {
// Pick a remaining element...
randomIndex = Math.floor(Math.random() * currentIndex);
currentIndex -= 1;
// And swap it with the current element.
temporaryValue = array[currentIndex];
array[currentIndex] = array[randomIndex];
array[randomIndex] = temporaryValue;
}
return array;
}
If you need the keys associated with the value, just use an array of objects. Instead of using "one", "two", "three", etc to identify each set, we can just use the index of the object in the array. For example:
var list = [
{"a" : "aa", "b": "bb", "c" : "cc"},
{"d" : "dd", "e": "ee", "f" : "ff"},
{"g" : "gg", "e": "hh", "i" : "ii"},
];
Then we'd use:
shuffle(list);
console.log(list[0]);
which should give us a randomized array of objects. Each time it ran it'd get a random object:
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
e: "hh",
g: "gg",
i: "ii"
}
[object Object] {
a: "aa",
b: "bb",
c: "cc"
}
Just grab the first item in the array after shuffling it, list[0] and use for-in loop to get the values:
var randomResult = list[0];
for (key in randomResult){
console.log(randomResult[key];
}
If you don't need the key associated with the value, i.e., "a" with "aa", and you just wanted to get a random selection from your values you can use an array and the Fisher-Yates (aka Knuth) Shuffle function.
For example:
var list = ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg']
We can then apply it to the array
shuffle(list)
and we'd get an array with the same values (no repeating) that is randomized and can be iterated over.
["cc", "ee", "bb", "gg", "aa", "ff", "dd"]
If you need values to be grouped together but you don't need the keys, i.e., you need 'aa', 'bb', 'cc' to always be returned together, you can use an array of arrays AKA a multidimensional array.
var list = [['aa', 'bb', 'cc'], ['dd', 'ee', 'ff'], ['gg', 'hh', 'ii']];
If we run the sorted function along with a little extra code we can get the three values
function sortedMulti(array){
sorted(array);
return array[0]
};
With this we'd get a random set each time.
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["aa", "bb", "cc"]
["dd", "ee", "ff"]
["gg", "hh", "ii"]
["gg", "hh", "ii"]
This would randomize the array, meaning you'd get a random set at the index 0 of the main array. You can then either return it (like I have) or iterate through the items in the array with a for loop to get each value.