Push in array only values ​that contain a certain string - javascript

I would like only data containing a certain string to be sent from my array to another array
for example
test=something
test1=something
test=testsadsad
If my array contains test=
My new array will be ['something', 'testsadsad']
This is my code.
let data = Object.values(args);
let serializedData = data.join("\n");
let newArray = [];
for (let i = 0; i < data.length; i++) {
if (data[i].includes("test=") === true) {
console.log(data[i])
newArray.push(data[i].split("test="));
}
}

You can modify your logic like this
//simulated data
const data = [
"test=something",
"test1=something",
"test=testsadsad",
]
let newArray = [];
for (let i = 0; i < data.length; i++) {
//`key` is `test` and `value` is `something`
const [key, value] = data[i].split("=") //splitted by `=`
if (key === "test") {
newArray.push(value);
}
}
console.log(newArray)

You are not formatting the data correctly when pushing onto the array.
let data = Object.values(args);
let newArray = [];
for (let i = 0; i < data.length; i++) {
if (data[i].includes("test=") === true) {
console.log(data[i])
// Note It looks like your problem is here
newArray.push(data[i].replace("test=", ''));
}
}

If your input array is data then this will return the desired output:
let output = data
.filter(item => item.includes("test="))
.map(item => item.split("test=")[1])
This filters the array by selecting all items that include test= and then maps each result to the substring after test=.

Related

Remove all anagrams from array

I need find and delete all anagrams from an array. All my attempts give ["bac","art"], but I need ["art"]
const deleteAnagrams = (arr) => {
let obj = {};
for (let i = 0; i < arr.length; i++) {
let sorted = arr[i].toLowerCase().split("").sort().join("");
obj[sorted] = arr[i];
}
return Object.values(obj);
};
console.log(deleteAnagrams(['cab', 'bac', 'art']))
You are actually storing unique strings with the last occurence to the object. But you need to remove duplicates and keep only singel occurences of same sorted strings.
To get the result, you need to filter the values.
const deleteAnagrams = array => {
const object = {};
for (const word of array) {
let sorted = word.toLowerCase().split("").sort().join("");
object[sorted] = sorted in object ? undefined : word;
}
return Object.values(object).filter(Boolean);
};
console.log(deleteAnagrams(['cab', 'bac', 'art']));

Information about to Array in JAvascript

I would like to get find elements having same characters but in different order in an array. I made javascript below,is there any way to create Javascript function more basic? Can you give me an idea? Thank you in advance..
<p id="demo"></p>
<script>
const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];
var sameChars = 0;
var subArr1 = [];
for(var i = 0; i < arr1.length; i++){
for(var j = i+1; j < arr1.length; j++){
if(!subArr1.includes(arr1[i]) && !subArr1.includes(sortAlphabets(arr1[i]))){
subArr1.push(arr1[i]);
sameChars++;
}
if(sortAlphabets(arr1[i]) == sortAlphabets(arr1[j])){
if(!subArr1.includes(arr1[j])){
subArr1.push(arr1[j]);
}
}
}
}
function sortAlphabets(text1) {
return text1.split('').sort().join('');
};
document.getElementById("demo").innerHTML = sameChars;
</script>
I would just use reduce. Loop over split the string, sort it, join it back. Use it as a key in an object with an array and push the items onto it.
const arr1 = ["tap", "pat", "apt", "cih", "hac", "ach"];
const results = arr1.reduce((obj, str) => {
const key = str.split('').sort().join('');
obj[key] = obj[key] || [];
obj[key].push(str);
return obj;
}, {});
console.log(Object.values(results));
You can get the max frequency value by building a map and getting the max value of the values.
const frequencyMap = (data, keyFn) =>
data.reduce(
(acc, val) =>
(key => acc.set(key, (acc.get(key) ?? 0) + 1))
(keyFn(val)),
new Map());
const groupMap = (data, keyFn) =>
data.reduce(
(acc, val) =>
(key => acc.set(key, [...(acc.get(key) ?? []), val]))
(keyFn(val)),
new Map());
const
data = ["tap", "pat", "apt", "cih", "hac", "ach"],
sorted = (text) => text.split('').sort().join(''),
freq = frequencyMap(data, sorted),
max = Math.max(...freq.values()),
groups = groupMap(data, sorted);
document.getElementById('demo').textContent = max;
console.log(Object.fromEntries(freq.entries()));
console.log(Object.fromEntries(groups.entries()));
.as-console-wrapper { top: 2em; max-height: 100% !important; }
<div id="demo"></div>
Maybe split the code into two functions - one to do the sorting and return a new array, and another to take that array and return an object with totals.
const arr = ['tap', 'pat', 'apt', 'cih', 'hac', 'ach'];
// `sorter` takes an array of strings
// splits each string into an array, sorts it
// and then returns the joined string
function sorter(arr) {
return arr.map(str => {
return [...str].sort().join('');
});
}
// `checker` declares an object and
// loops over the array that `sorter` returned
// creating keys from the strings if they don't already
// exist on the object, and then incrementing their value
function checker(arr) {
const obj = {};
for (const str of arr) {
// All this line says is if the key
// already exists, keep it, and add 1 to the value
// otherwise initialise it with 0, and then add 1
obj[str] = (obj[str] || 0) + 1;
}
return obj;
}
// Call `checker` with the array from `sorter`
console.log(checker(sorter(arr)));
<p id="demo"></p>
Additional documentation
map
Loops and iteration
Spread syntax

Is there a way to store index of an array and get its value back?

here is the task: I am trying to build an anagram finder which receives a given string (simple word) from an input, then check in a dictionary (of 350k words) and then return all the anagrams of that word. Here is where I got so far:
const button = document.getElementById("findButton");
button.addEventListener("click", function() {
let typedText = document.getElementById("input").value;
let wordIn = typedText.toLowerCase().split("").sort().join("").trim();
let output = [];
for (let i = 0; i < dictionary.length; i++) {
if (dictionary[i].length === wordIn.length)
output.push(dictionary[i])
}
let sorted = [];
let result = [];
for (let i = 0; i < output.length; i++) {
sorted.push(output[i].toLowerCase().split("").sort().join("").trim())
if (wordIn === sorted[i]) {
result.push(sorted[i])
}
}
});
With the current approach I get as final output an array with words alphabeticaly sorted i.e.: cat ("act", "act", "act"...) , but I need them as they are in the dictionary. I was thinking if I could store the index of the words in the output array (which already reduces from 350k to only those with same length) and after temporary sort them by their alphabetic value, I could get only those which match and return them as a new array. i.e cat = "cat", "act", "tac".
You can use filter:
const
// Once, at the top of your script:
normalizeWord = w => w.toLowerCase().split("").sort().join("").trim(),
dictionary = ['foo', 'act', 'bar', 'cat', 'example', 'word'],
sortedDict = dictionary.map(normalizeWord),
// In your event handler, or its own named function:
wordIn = normalizeWord('tac'),
result = dictionary.filter((_, i) => sortedDict[i] === wordIn);
console.log(result);
You can first of all increase your performance by getting the desired result in the first loop itself, thus no requirement of extra array and extra loop saving space and time.
const button = document.getElementById("findButton");
button.addEventListener("click", function() {
let typedText = document.getElementById("input").value;
let wordIn = typedText.toLowerCase().split("").sort().join("").trim();
let output = []; //it will have your final anagram list
for (let i = 0; i < dictionary.length; i++) {
let sortedWord = dictionary[i].toLowerCase().split("").sort().join("").trim();
if (sortedWord === wordIn) {
output.push(dictionary[i]);
}
}
});
Instead of result.push(sorted[i])
You should result.push(output[i]) instead.

Array: Merge keys and values, to call as an object

How to code a pure JS.
To call this content:
var keys = ["height", "width"];
var values = [["12px", "24px"],["127px", "284px"]...];
Into readable referral object:
Simple values_line[1].height
may return
127px
Try this code:
var array = keys.map((el, i) => { return [keys[i], values[i]]; });
But it work only to match key to value One time only.
console.log(array);
// → [["height", "12px"], ["width", "24px"]]
var output = Object.fromEntries(array);
// → {height: "12px", width: "24px"}
console.log(output);
or even
var result = {};
for (var i = 0; i < keys.length; i++)
result[keys[i]] = values[i];
Any idea to create object of full "table" with title/head names?
For each value, map over the keys array to create a tuple of [key, value], then use Object.fromEntries to construct your object.
var keys = ["height", "width"];
var values = [["12px", "24px"],["127px", "284px"]];
var dimensions = values.map(value => (
Object.fromEntries(keys.map((key, index) => ([key, value[index]])))
));
console.log(dimensions);
Iterate over values using Array#map.
At each iteration, create an object from keys using Array#reduce representing key-value pairs, where its values are from the current list according to the index:
const
keys = ["height", "width"],
values = [["12px", "24px"],["127px", "284px"]];
const values_line = values.map(currentValues =>
keys.reduce((acc, key, index) => ({ ...acc, [key]: currentValues[index]}), {})
);
console.log(values_line);
Using for-loops:
const
keys = ["height", "width"],
values = [["12px", "24px"],["127px", "284px"]];
const values_line = [];
for(let i = 0; i < values.length; i++) {
const currentValues = values[i];
const currentObj = {};
for(let j = 0; j < keys.length; j++) {
const key = keys[j];
currentObj[key] = currentValues[j];
}
values_line[i] = currentObj;
}
console.log(values_line);

How to access elements of arrays within array (JavaScript)?

I'm trying to access elements from a JavaScript array:
[["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]]
I want to access
1, 2, 3, 4, 5, 6 separately in a variable and John, Rajan, Hitesh, Vin, Ritwik, Sherry separately in a variable.
I tried converting it to a string and split(), but it doesn't work.
this is code i tried
var jArray = <?php echo json_encode($newarray); ?> ;
var nJarr = jArray[0]; nJarr.toString();
var res = nJarr.split(","); var apname = res[0];
alert(apname);
but there's no alert appearing on the screen
If you are open to using Underscore, then it's just
var transposed = _.zip.apply(0, arr);
and the arrays you are looking for will be in transposed[0] and transposed[1].
You can write your own transpose function fairly easily, and it's more compact if you can use ES6 syntax:
transpose = arr => Object.keys(arr[0]).map(i => arr.map(e => e[i]));
>> transpose([["1","John"], ["2","Rajan"], ...]]
<< [[1, 2, ...], ["John", "Rajan", ...]]
If you want an ES5 version, here's one with comments:
function transpose(arr) { // to transpose an array of arrays
return Object.keys(arr[0]) . // get the keys of first sub-array
map(function(i) { // and for each of these keys
arr . // go through the array
map(function(e) { // and from each sub-array
return e[i]; // grab the element with that key
})
))
;
}
If you prefer old-style JS:
function transpose(arr) {
// create and initialize result
var result = [];
for (var i = 0; i < arr[0].length; i++ ) { result[i] = []; }
// loop over subarrays
for (i = 0; i < arr.length; i++) {
var subarray = arr[i];
// loop over elements of subarray and put in result
for (var j = 0; j < subarray.length; j++) {
result[j].push(subarray[j]);
}
}
return result;
}
Do it like bellow
var arr = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var numbers = arr.map(function(a){return a[0]}); //numbers contain 1,2,3,4,5
var names = arr.map(function(a){return a[1]}); //names contain John,Rajan...
Try this:
var data = [["1","John"],["2","Rajan"],["3","Hitesh"],["4","Vin"],["5","ritwik"],["6","sherry"]];
var IDs = [];
var names = [];
for(i=0; i<data.length; i++)
{
IDs.push(data[i][0]);
names.push(data[i][1]);
}
console.log(IDs);
console.log(names);
Here is the working fiddle.

Categories

Resources