javascript loop and push into every next index - javascript

function addItemEvery(arr, item, starting, frequency) {
for (var i = 0, a = []; i < arr.length; i++) {
a.push(arr[i]);
if ((i + 1 + starting) % frequency === 0) {
a.push(item);
i++;
if(arr[i]) a.push(arr[i]);
}
}
return a;
}
var arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
arr = addItemEvery(arr, "item", 1, 1);
console.log(arr);
What I get
[1, "item", 2, 3, "item", 4, 5, "item", 6, 7, "item", 8, 9, "item", 10, 11, "item", 12, 13,
"item", 14, 15, "item", 16]
What i want
[1, "item", 2,"item", 3, "item", 4,"item", 5,"item", "item", 6,"item", 7, "item", 8,"item",
9,"item", "item", 10,"item", 11, "item", 12,"item", 13, "item", 14,"item", 15, "item", 16, "item"]
so please help me check this out i need a function that can help me push to all n index in the array

This will give you the output you desire.
var array = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16],
pos = 1;
interval = 2;
while (pos < array.length) {
array.splice(pos, 0, 'item');
pos += interval;
}
console.log(array);

The base version (excluding the starting and frequency arguments) can be done with a single call to Array#reduce like this. I've excluded starting and frequency since you didn't define their intended behaviour in your question.
const addItemEvery = (arr, el) =>
arr.reduce((res, v) => [...res, v, el], []);
const input = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16];
const output = addItemEvery(input, "item");
console.log(output);

function addItemEvery(arr, item, starting, frequency) {
const newArr = [];
arr.forEach((entry, index) => {
newArr.push(entry);
if (index + 1 >= starting)
for (let i = 1; i <= frequency; i++) {
newArr.push(item);
}
});
return newArr;
}

Related

JavaScript: Change all repeated values to 0 in array

I have an array with duplicate values
let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
I want to set the repeated values to 0:
[0, 0, 0, 0, 7, 8, 0, 0, 2, 0, 6, 4, 0]
can find out the repeated value, but I want to change the repeated value to 0, is there any better way?
let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
Array.prototype.duplicate = function () {
let tmp = [];
this.concat().sort().sort(function (a, b) {
if (a == b && tmp.indexOf(a) === -1) tmp.push(a);
});
return tmp;
}
console.log(ary.duplicate()); // [ 1, 3, 5, 9 ]
// ? ary = [0, 0, 0, 0, 7, 8, 0, 0, 2, 0, 6, 4, 0];
You could use indexOf() and lastIndexOf() method to solve your problem.
const array = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
const ret = array.map((x) =>
array.indexOf(x) !== array.lastIndexOf(x) ? 0 : x
);
console.log(ret);
const ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
// get set of duplicates
let duplicates = ary.filter((elem, index, arr) => arr.indexOf(elem) !== index)
duplicates = new Set(duplicates);
// set duplicate elements to 0
const res = ary.map(e => duplicates.has(e) ? 0 : e);
console.log(...res);
First, count values and store them in an object. Then loop over the array and check from that stored object whether the count of specific value is greater than 1 or not, if greater than 1, set that to 0. Here is the working example:
let ary = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
let countValue = {}, len = ary.length;
for (i = 0; i < len; i++) {
if (countValue[ary[i]]) {
countValue[ary[i]] += 1;
} else {
countValue[ary[i]] = 1;
}
}
for (i = 0; i < len; i++) {
if (countValue[ary[i]] > 1) {
ary[i] = 0;
}
}
console.log(...ary);
Probably this is the quickest algorithm, though it will alter your original array.
const array = [5, 1, 3, 5, 7, 8, 9, 9, 2, 1, 6, 4, 3];
const map = {};
for (let ind = 0; ind < array.length; ind++) {
const e = array[ind];
if (map[e] === undefined) {
map[e] = ind;
} else {
array[map[e]] = 0;
array[ind] = 0;
}
}
console.log(...array);

How object hash works to remove duplicates in this scenario?

function distinctUnion(arr, arr2) {
let merged = [...arr, ...arr2];
var result = [];
var map = {}
for (let i = 0; i < merged.length; i++) {
if (!map.hasOwnProperty(merged[i])) {
map[merged[i]] = true; // Line 3 --> if I remove this line, it prints duplicates
console.log('map', JSON.stringify(map, 2, null));
result.push(merged[i]);
}
}
return result;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('unique ', JSON.stringify(distinctUnion(arr, arr2), 2, null));
All we are setting here is map[merged[i]] = true; for all keys in object
map {"3":true,"4":true,"5":true,"6":true,"8":true,"9":true,"10":true,"11":true}
then how result.push(merged[i]) has only unique values?
I mean to say merged[i] inside loop should still have all array values including duplicates right?
I am not able to understand the link between map[merged[i]] = true; and result.push(merged[i])
If you do not set the property to anything, map.hasOwnProperty(...) will spuriously return false for the next time that value is encountered, thus allowing duplicates. You don't need to set it to true, as it is just used to indicate the presence of a key; any value is fineā€”even undefined!
function distinctUnion(arr, arr2) {
let merged = [...arr, ...arr2];
var result = [];
var map = {}
for (let i = 0; i < merged.length; i++) {
if (!map.hasOwnProperty(merged[i])) {
map[merged[i]] = undefined;
result.push(merged[i]);
}
}
return result;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('unique ', JSON.stringify(distinctUnion(arr, arr2), 2, null));
To make your code works, you just need to replace map[merged[i]] = true; with map[merged[i]] = undefined;.
However, you can make your function more simplified as follows:
function distinctUnion(arr, arr2) {
let map = {};
[...arr, ...arr2].forEach((x)=>{map[x] = x});
return Object.values(map);;
}
let arr = [3, 4, 5, 6, 6, 4, 5, 8, 9, 10, 10];
let arr2 = [11, 11, 11, 4, 4, 4, 5, 5, 5, 6, 6, 6, 6];
console.log('Unique ', distinctUnion(arr, arr2));

Parse this Json response and loop through the array in JavaScript

There are many post about this but I can't figure this one out. This is the json response from an Ajax function:
var obj = {
"3901": 10,
"3900": 3,
"3902": 9,
"3899": 2,
"3274": 4,
"3257": 9.5,
"3883": 12,
"3881": "12",
"3876": 3,
"3267": 14,
"3258": 2.5,
"3260": 13.5,
"3259": 6.5,
"3264": 4.5,
"3268": 2,
"3273": 5.5,
"3266": 17,
"3270": 9,
"3271": 8,
"3275": 2,
"3263": 2.5,
"3261": 2.5,
"3265": "37",
"3281": 3,
"3277": 7.5,
"3278": 0.5,
"3276": 7,
"3898": 8,
"3891": 7,
"3293": 1,
"3895": 1,
"3256": 2,
"3903": 10,
"3840": 2,
"3886": 11,
"3884": 8,
"3872": 2,
"3874": 4,
"3284": 1.5,
"3302": 1.25,
"3304": 5,
"3306": 2,
"3329": 1.5,
"3330": 2,
"3333": 6,
"3335": 7.5,
"3327": 1,
"3934": 8,
"3935": 9,
"3939": 1,
"3933": 3,
"3937": 1,
"3322": 3.5,
"3890": 1,
"3878": 5,
"3880": 4,
"3879": 1,
"3889": 2,
"3852": 2,
"3877": 2
}
I have a this of ids: 3902, 3883, 4567 and 3878
All I need is to loop through the those 4 ids and check if those are in the json response and if they are get the value associated to it and if not return 0. For example:
3902 will return 9 and 4567 will return 0
Thanks.
You can put all the ids into an array called ids, then use .map() on that array. For each id within the array, you can look it up in your object using obj[id]. If it doesn't exist, it will return undefined. If this occurs, you can use a default of 0 by using an ||:
See example below:
const obj = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
const ids = [3902, 3883, 4567, 3878];
const res = ids.map(id => obj[id] || 0);
console.log(res);
var jsonObject = {3256: 2, 3257: 9.5, 3258: 2.5, 3259: 6.5, 3260: 13.5, 3261: 2.5, 3263: 2.5, 3264: 4.5, 3265: "37", 3266: 17, 3267: 14, 3268: 2, 3270: 9, 3271: 8, 3273: 5.5, 3274: 4, 3275: 2, 3276: 7, 3277: 7.5, 3278: 0.5, 3281: 3, 3284: 1.5, 3293: 1, 3302: 1.25, 3304: 5, 3306: 2, 3322: 3.5, 3327: 1, 3329: 1.5, 3330: 2, 3333: 6, 3335: 7.5, 3840: 2, 3852: 2, 3872: 2, 3874: 4, 3876: 3, 3877: 2, 3878: 5, 3879: 1, 3880: 4, 3881: "12", 3883: 12, 3884: 8, 3886: 11, 3889: 2, 3890: 1, 3891: 7, 3895: 1, 3898: 8, 3899: 2, 3900: 3, 3901: 10, 3902: 9, 3903: 10, 3933: 3, 3934: 8, 3935: 9, 3937: 1, 3939: 1}
var ids = [3902, 3883, 4567, 3878];
for(var i =0; i < ids.length; i++)
{
if(temp1.hasOwnProperty(ids[i])) //to check propery exist in JSON object
{
console.log(temp1[ids[i]]) //to read value from JSON object
}
}
I think you already have a valid JSON here.
let data = {"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2};
let arr = [3902, 3883, 4567 , 3878];
let ans = arr.map( i => {
if(data[i] === undefined) {
console.log(0);
return 0;
}
else {
console.log(data[i]);
return data[i];
}
});
ans is the required array .
You can use a foreach
j={"3901":10,"3900":3,"3902":9,"3899":2,"3274":4,"3257":9.5,"3883":12,"3881":"12","3876":3,"3267":14,"3258":2.5,"3260":13.5,"3259":6.5,"3264":4.5,"3268":2,"3273":5.5,"3266":17,"3270":9,"3271":8,"3275":2,"3263":2.5,"3261":2.5,"3265":"37","3281":3,"3277":7.5,"3278":0.5,"3276":7,"3898":8,"3891":7,"3293":1,"3895":1,"3256":2,"3903":10,"3840":2,"3886":11,"3884":8,"3872":2,"3874":4,"3284":1.5,"3302":1.25,"3304":5,"3306":2,"3329":1.5,"3330":2,"3333":6,"3335":7.5,"3327":1,"3934":8,"3935":9,"3939":1,"3933":3,"3937":1,"3322":3.5,"3890":1,"3878":5,"3880":4,"3879":1,"3889":2,"3852":2,"3877":2}
se=[3902, 3883, 4567 , 3878]
res=[]
se.forEach(s=>{
res.push({[s]:j[s]||0})
})
console.log(res)

Getting a "not defined" error in my JavaScript code when I think it is defined

I am working on a project for SkillCrush and am getting a "not defined" error, when I feel as though I've defined the variable at the top of the code. I 100% know I'm doing something wrong, but not sure what. Any suggestions?
var createPolitician = function (name)
{
var politician = {}; //is this not defined here?
politician.name = name;
politician.electionResults = null;
politician.totalVotes = 0;
return politician;
};
var oscar = createPolitician("Oscar Jiminez");
var luke = createPolitician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
console.log(oscar.electionResults);
console.log(luke.electionResults);
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++);
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
oscar.countTotalVotes();
luke.countTotalVotes();
console.log(oscar.totalVotes);
console.log(luke.totalVotes);
Error:
"error"
"ReferenceError: politician is not defined
at reloyur.js:32:1"
politician.countTotalVotes = ...
That won't work as politician only exists while you create luke or oscar (it then points to one of them). Instead you could do:
luke.countTotalVotes = oscar.countTotalVotes = function() { /*...* };
But for more politicians that gets a bit complicated. You could however just make a function that you pass a politician into:
function countTotalVotes(politician) {
//...
}
countTotalVotes(luke);
Or you use the power of inheritance.
As I suggested in comments, you can rewrite Politician as a class, which basically gives you a template for reusable functionality. If you're not familiar with the concept, a good google term would be "prototypal inheritance" for follow-up on the subject in general. For now, here's a rewrite of your script using a class:
class Politician {
constructor (name) {
this.name = name;
this.electionResults = [];
}
// no need to even write a .countTotalVotes() method
// just define .totalVotes as a getter that does the work
get totalVotes () {
var total = 0;
for (var i = 0; i < this.electionResults.length; i++) {
total += this.electionResults[i];
}
return total;
}
}
var oscar = new Politician("Oscar Jiminez");
var luke = new Politician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
// console.log(oscar.electionResults);
// console.log(luke.electionResults);
// these are no longer required
// oscar.countTotalVotes();
// luke.countTotalVotes();
console.log(oscar.name, 'has', oscar.totalVotes, 'votes');
console.log(luke.name, 'has', luke.totalVotes, 'votes');
Move your countTotalVotes function into your create function:
var createPolitician = function (name)
{
var politician = {};
politician.name = name;
// set to an empty array so this is defined
politician.electionResults = [];
politician.totalVotes = 0;
// here politician exists, add a function to the object that you can call later
politician.countTotalVotes = function()
{
this.totalVotes = 0;
for (var i = 0; i < this.electionResults.length; i++)
{
this.totalVotes = this.totalVotes + this.electionResults[i];
}
}
return politician;
};
I corrected your mistakes in your code. You could change your code like follows:
function createPolitician(name)
{
var politician =
{
name: name,
electionResults: null,
totalVotes: 0,
countTotalVotes: function()
{
//this.totalVotes = 0; <- irrelevant because you use it only one time
for(var i = 0; i < this.electionResults.length; i++)//";" symbol on the end is your mistake too
{
this.totalVotes += this.electionResults[i];
}
}
};
return politician;
};
var oscar = createPolitician("Oscar Jiminez");
var luke = createPolitician("Luke Spencer");
oscar.electionResults = [5, 1, 7, 2, 33, 6, 4, 2, 1, 14, 8, 3, 1, 11, 11, 0, 5, 3, 3, 3, 7, 4, 8, 9, 3, 7, 2, 2, 4, 2, 8, 3, 15, 15, 2, 12, 0, 4, 13, 1, 3, 2, 8, 21, 3, 2, 11, 1, 3, 7, 2];
luke.electionResults = [4, 2, 4, 4, 22, 3, 3, 1, 2, 15, 8, 1, 3, 9, 0, 6, 1, 5, 5, 1, 3, 7, 8, 1, 3, 3, 1, 3, 2, 2, 6, 2, 14, 0, 1, 6, 7, 3, 7, 3, 6, 1, 3, 17, 3, 1, 2, 11, 2, 3, 1];
oscar.electionResults[9] = 1;
luke.electionResults[9] = 28;
oscar.electionResults[4] = 17;
luke.electionResults[4] = 38;
oscar.electionResults[43] = 11;
luke.electionResults[43] = 27;
console.log(oscar.electionResults);
console.log(luke.electionResults);
oscar.countTotalVotes();
luke.countTotalVotes();
console.log(oscar.name, 'has', oscar.totalVotes, 'votes');
console.log(luke.name, 'has', luke.totalVotes, 'votes');
The error message should be accompanied with a line and column number. In this case, the error is occurring on line 32:
politician.countTotalVotes = function()
In the definition of the createPolitician function, you declared a variable named politician. var creates a variable that lives within the function it was declared in. If it is not inside of a function, it creates a global variable.
You left the function the variable was declared in, and thus it isn't usable anymore.
If you think about it, it'd be very ambiguous if you could re-use that politician variable later on. What would it refer to?
If you want to be able to call countTotalVotes() on the politicians, then Patrick's comment about using a Class is a good approach to take. You could also assign the function to the politician object that you return from createPolitician - this would give each instance of the politician its own copy of the function.
It's all about variable scope. Declare the politician object variable outside of the createPolitician function for you to access out of the function. It cannot be accessed out of its scope that is why you get an undefined error.

Add new items and slice from the top Javascript

I have a list with items like:
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
I want, for every scroll, to add 15th new items and then to slice from the top another 15th elements.
Can you help me? Thanks!!!
Updated:
getMoreItems(items: any) {
var lastIndex: number;
if (items.visible.length) {
var lastItem: any = _.last(items.visible);
lastIndex = _.findLastIndex(items.allValues, { Name: lastItem.Name });
}
var startIndex = lastIndex + 1 || 0;
var endIndex = Math.min(startIndex + 15, items.allValues.length);
var newItems = items.allValues.slice(startIndex, endIndex);
if (items.visible.length > 30) {
items.visible = items.visible.slice(0, 15).concat(newItems);
} else {
items.visible = items.visible.concat(newItems);
}
}
var values = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, ...];
values = values.splice(0,15); // remove first 15 items
values = values.concat([another 15 items]); // add next 15
And of course you can inline this:
values = values.splice(0,15).concat([x1...x2])
Something like this?
var numbers = [1,2,3,4,5,6,7,8,9,10];
numbers = numbers.slice(2).concat([11,12]);
console.log(numbers);
>> [ 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 ]
if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
scroll=[32, 232,23, 232, 23, 232, 23,238, 92, 120];
old=scroll;
console.log(old);
and if you ahve items one by one then you can use pattern:
if you have array on scroll you can reinitialize your array:
var old= [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
old.push(next_value);
old.shift()
console.log(old);

Categories